/* Volaire — account: dashboard, trips, trip detail, protection portal slot #2, profile, payment */

function RequireAuth({ children }) {
  const session = useSession();
  useEffect(function () {
    if (!session) navigate('/login');
  }, [session]);
  if (!session) return null;
  return children;
}

function AccountNav({ current }) {
  const { t } = useLang();
  const items = [
    { to: '/account', label: t('nav.account') },
    { to: '/account/trips', label: t('account.tile.trips') },
    { to: '/account/protection', label: t('account.tile.protection') },
    { to: '/account/profile', label: t('account.tile.profile') },
    { to: '/account/payment', label: t('account.tile.payment') },
  ];
  return (
    <nav aria-label={t('nav.account')} className="flex gap-1 overflow-x-auto pb-1">
      {items.map(function (it) {
        const active = current === it.to;
        return (
          <Link key={it.to} to={it.to}
            className={'shrink-0 rounded-lg px-3 py-1.5 text-sm font-medium ' + (active ? 'bg-cobalt/10 text-cobalt' : 'text-muted hover:bg-white hover:text-ink')}>
            {it.label}
          </Link>
        );
      })}
    </nav>
  );
}

/* ---------- dashboard ---------- */
function AccountPage() {
  const { t, lang } = useLang();
  const session = useSession();
  const trips = L.loadTrips();
  const upcoming = trips.filter(function (x) { return (x.status === 'confirmed' || x.status === 'checked-in'); })
    .sort(function (a, b) { return new Date(a.outbound.departTime) - new Date(b.outbound.departTime); });
  const next = upcoming[0];
  const days = next ? L.daysUntil(next.outbound.departTime.slice(0, 10)) : null;
  const countdown = days == null ? '' : days === 0 ? t('account.nextTrip.countdown.today') : days === 1 ? t('account.nextTrip.countdown.one') : t('account.nextTrip.countdown').replace('{n}', days);
  const protectedCount = trips.filter(function (x) { return x.protection && x.status !== 'cancelled'; }).length;
  const tiles = [
    { to: '/account/trips', icon: 'plane', title: t('account.tile.trips'), desc: t('account.tile.trips.desc'), count: upcoming.length },
    { to: '/account/protection', icon: 'shield', title: t('account.tile.protection'), desc: t('account.tile.protection.desc'), count: protectedCount },
    { to: '/account/profile', icon: 'user', title: t('account.tile.profile'), desc: t('account.tile.profile.desc') },
    { to: '/account/payment', icon: 'card', title: t('account.tile.payment'), desc: t('account.tile.payment.desc'), count: 1 },
  ];
  return (
    <RequireAuth>
      <main className="mx-auto max-w-6xl px-4 pt-6" data-screen-label="Account dashboard">
        <AccountNav current="/account"></AccountNav>
        <div className="mt-4 flex flex-wrap items-center justify-between gap-3">
          <h1 className="text-3xl font-bold tracking-tight text-ink">{t('account.greeting')}, {session ? session.firstName : ''}</h1>
          <button className="text-sm font-medium text-muted hover:text-danger" onClick={function () { L.setSession(null); navigate('/'); }}>{t('account.signOut')}</button>
        </div>
        {next ? (
          <section aria-label={t('account.nextTrip')} className="mt-5 overflow-hidden rounded-xl border border-line bg-white">
            <div className="bg-gradient-to-r from-cobalt to-cobaltDark px-5 py-2.5">
              <p className="text-xs font-bold uppercase tracking-widest text-white/85">{t('account.nextTrip')} · {countdown}</p>
            </div>
            <div className="flex flex-wrap items-center justify-between gap-4 p-5">
              <div>
                <p className="text-2xl font-bold tabular-nums tracking-tight text-ink">
                  {next.outbound.origin} <span className="font-normal text-muted">→</span> {next.outbound.destination}
                </p>
                <p className="mt-0.5 text-sm capitalize text-muted">
                  {L.fmtDateLong(next.outbound.departTime, lang)} · {L.fmtTime(next.outbound.departTime)} · {next.outbound.flightNumber} · PNR {next.pnr}
                </p>
              </div>
              <div className="flex flex-wrap gap-2">
                {next.status === 'confirmed' ? (
                  <Link to={'/checkin?pnr=' + next.pnr} className="rounded-lg bg-cobalt px-5 py-2.5 text-sm font-bold text-white hover:bg-cobaltDark">{t('account.trip.checkin')}</Link>
                ) : <StatusPill status={next.status}></StatusPill>}
                <Link to={'/account/trips/' + next.pnr} className="rounded-lg border border-line px-5 py-2.5 text-sm font-semibold text-ink hover:border-cobalt">{t('account.nextTrip.view')}</Link>
              </div>
            </div>
          </section>
        ) : null}
        <div className="mt-5 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
          {tiles.map(function (tl) {
            return (
              <Link key={tl.to} to={tl.to} className="group rounded-xl border border-line bg-white p-5 transition-colors hover:border-cobalt">
                <div className="flex items-start justify-between">
                  <span className="flex h-10 w-10 items-center justify-center rounded-lg bg-cobalt/10 text-cobalt"><Icon name={tl.icon} size={20}></Icon></span>
                  {tl.count != null ? <span className="rounded-full bg-page px-2 py-0.5 text-xs font-bold tabular-nums text-muted">{tl.count}</span> : null}
                </div>
                <p className="mt-3 font-bold text-ink group-hover:text-cobalt">{tl.title}</p>
                <p className="mt-0.5 text-sm text-muted">{tl.desc}</p>
              </Link>
            );
          })}
        </div>
        <section aria-label={t('account.inspirations')} className="mt-10">
          <h2 className="text-lg font-bold tracking-tight text-ink">{t('account.inspirations')}</h2>
          <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-3">
            {['FCO', 'LIS', 'AMS'].map(function (code, i) {
              return <DestinationTile key={code} code={code} price={[44, 49, 54][i]}
                onSearch={function () { navigate('/search?' + new URLSearchParams({ from: 'CDG', to: code, depart: L.todayISO(21), 'return': L.todayISO(25), cabin: 'economy', type: 'round-trip' }).toString()); }}></DestinationTile>;
            })}
          </div>
        </section>
      </main>
    </RequireAuth>
  );
}

/* ---------- trips list ---------- */
function TripRow({ trip }) {
  const { t, lang } = useLang();
  return (
    <Link to={'/account/trips/' + trip.pnr}
      className="grid grid-cols-[1fr_auto] items-center gap-x-4 gap-y-1 rounded-xl border border-line bg-white p-4 transition-colors hover:border-cobalt sm:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_auto_auto]">
      <span className="flex items-center gap-2 text-base font-bold tabular-nums tracking-tight text-ink">
        {trip.outbound.origin}<Icon name={trip.tripType === 'round-trip' ? 'swap' : 'arrowRight'} size={14} className="rotate-90 text-muted sm:rotate-90"></Icon>{trip.outbound.destination}
      </span>
      <span className="text-sm capitalize text-muted">
        {L.fmtDateShort(trip.outbound.departTime, lang)}{trip.inbound ? ' — ' + L.fmtDateShort(trip.inbound.departTime, lang) : ''}
      </span>
      <span className="text-xs font-semibold tabular-nums text-muted">PNR {trip.pnr}</span>
      <span className="flex items-center justify-end gap-3">
        <StatusPill status={trip.status}></StatusPill>
        <span className="hidden text-sm font-semibold text-cobalt sm:inline">{t('account.trips.details')} →</span>
      </span>
    </Link>
  );
}
function AccountTripsPage() {
  const { t } = useLang();
  const trips = L.loadTrips();
  const upcoming = trips.filter(function (x) { return x.status === 'confirmed' || x.status === 'checked-in'; })
    .sort(function (a, b) { return new Date(a.outbound.departTime) - new Date(b.outbound.departTime); });
  const past = trips.filter(function (x) { return x.status === 'completed' || x.status === 'cancelled'; });
  return (
    <RequireAuth>
      <main className="mx-auto max-w-4xl px-4 pt-6" data-screen-label="Trips list">
        <AccountNav current="/account/trips"></AccountNav>
        <h1 className="mt-4 text-3xl font-bold tracking-tight text-ink">{t('account.trips.title')}</h1>
        {[{ k: 'account.trips.upcoming', list: upcoming }, { k: 'account.trips.past', list: past }].map(function (g) {
          return (
            <section key={g.k} aria-label={t(g.k)} className="mt-6">
              <h2 className="text-xs font-bold uppercase tracking-wider text-muted">{t(g.k)}</h2>
              <div className="mt-2 flex flex-col gap-2">
                {g.list.length === 0 ? <p className="rounded-xl border border-line bg-white p-4 text-sm text-muted">{t('account.trips.none')}</p> : null}
                {g.list.map(function (trip) { return <TripRow key={trip.pnr} trip={trip}></TripRow>; })}
              </div>
            </section>
          );
        })}
      </main>
    </RequireAuth>
  );
}

/* ---------- trip detail ---------- */
function ItineraryCard({ f, seat, fareFamily, label }) {
  const { t, lang } = useLang();
  const terminal = f.origin === 'CDG' ? '2F' : f.origin === 'ORY' ? '3' : '1';
  return (
    <div className="rounded-xl border border-line bg-white p-4 sm:p-5">
      <div className="flex items-center justify-between">
        <span className="text-xs font-bold uppercase tracking-wider text-muted">{label}</span>
        <span className="text-xs capitalize text-muted">{L.fmtDateLong(f.departTime, lang)}</span>
      </div>
      <div className="mt-3 flex items-center gap-5">
        <div>
          <p className="text-2xl font-bold tabular-nums tracking-tight text-ink">{L.fmtTime(f.departTime)}</p>
          <p className="text-sm font-semibold tabular-nums text-muted">{f.origin} · T{terminal}</p>
        </div>
        <div className="flex min-w-[80px] flex-1 flex-col items-center gap-0.5">
          <span className="text-xs tabular-nums text-muted">{L.fmtDuration(f.durationMin)}</span>
          <span className="relative h-px w-full bg-line"><span className="absolute -top-2 left-1/2 -translate-x-1/2 bg-white px-1 text-cobalt"><Icon name="plane" size={14}></Icon></span></span>
          <span className="text-xs text-muted">{f.flightNumber} · {f.aircraft}</span>
        </div>
        <div>
          <p className="text-2xl font-bold tabular-nums tracking-tight text-ink">{L.fmtTime(f.arriveTime)}</p>
          <p className="text-sm font-semibold tabular-nums text-muted">{f.destination}</p>
        </div>
      </div>
      <div className="mt-3 flex flex-wrap items-center gap-2 border-t border-line pt-3">
        <FareFamilyPill fare={fareFamily}></FareFamilyPill>
        <span className="text-sm text-muted">{t('checkin.seat')} <span className="font-bold tabular-nums text-ink">{seat || '—'}</span></span>
      </div>
    </div>
  );
}
function AccountTripDetailPage({ pnr }) {
  const { t } = useLang();
  const [modal, setModal] = useState(false);
  const [, force] = useState(0);
  const trip = L.findTrip(pnr);
  if (!trip) {
    return (
      <main className="mx-auto max-w-4xl px-4 py-16 text-center">
        <p className="text-lg font-bold text-ink">{t('checkin.notFound')}</p>
        <Link to="/account/trips" className="mt-4 inline-block text-sm font-semibold text-cobalt hover:underline">← {t('account.trips.title')}</Link>
      </main>
    );
  }
  const seatOut = (trip.seats.find(function (s) { return s.flightId === 'out'; }) || {}).seat;
  const seatIn = (trip.seats.find(function (s) { return s.flightId === 'in'; }) || {}).seat;
  const upcoming = trip.status === 'confirmed' || trip.status === 'checked-in';
  const e = trip.extras || {};
  const extras = [];
  if ((e.checkedBags || 0) > 0 || L.FARE_RULES[trip.fareFamily].checkedBag) extras.push(t('booking.options.checkedBag'));
  if ((e.extraBags || 0) > 0) extras.push(t('booking.options.extraBag') + ' ×' + e.extraBags);
  if (e.priority || L.FARE_RULES[trip.fareFamily].priority) extras.push(t('booking.options.priority'));
  if (e.meal) extras.push(t('booking.options.meal') + ' — ' + t('booking.options.meal.' + (e.meal === 'gluten-free' ? 'glutenFree' : e.meal)));
  if (e.sportsEquipment) extras.push(t('booking.options.sports'));
  return (
    <RequireAuth>
      <main className="mx-auto max-w-4xl px-4 pt-6" data-screen-label="Trip detail">
        <Breadcrumb items={[{ label: t('nav.account'), to: '/account' }, { label: t('account.trips.title'), to: '/account/trips' }, { label: trip.pnr }]}></Breadcrumb>
        <div className="mt-4 flex flex-wrap items-center justify-between gap-3">
          <div className="flex items-center gap-3">
            <h1 className="text-3xl font-bold tabular-nums tracking-tight text-ink">{trip.outbound.origin} → {trip.outbound.destination}</h1>
            <StatusPill status={trip.status}></StatusPill>
          </div>
          <p className="text-sm text-muted">PNR <span className="font-bold tabular-nums text-ink">{trip.pnr}</span> · {t('account.trip.totalPaid')} <span className="font-bold tabular-nums text-ink">{L.fmtEUR(trip.total)}</span></p>
        </div>
        <div className="mt-5 flex flex-col gap-3">
          <ItineraryCard f={trip.outbound} seat={seatOut} fareFamily={trip.fareFamily} label={t('booking.seats.outbound')}></ItineraryCard>
          {trip.inbound ? <ItineraryCard f={trip.inbound} seat={seatIn} fareFamily={trip.fareFamily} label={t('booking.seats.return')}></ItineraryCard> : null}
        </div>
        {extras.length ? (
          <section aria-label={t('account.trip.optionsTitle')} className="mt-4 rounded-xl border border-line bg-white p-4">
            <h2 className="text-xs font-bold uppercase tracking-wider text-muted">{t('account.trip.optionsTitle')}</h2>
            <ul className="mt-2 flex flex-wrap gap-2">
              {extras.map(function (x, i) { return <li key={i} className="rounded-full bg-page px-3 py-1 text-sm text-ink">{x}</li>; })}
            </ul>
          </section>
        ) : null}
        {upcoming || trip.status === 'checked-in' ? (
          <div className="mt-4 flex flex-wrap gap-2">
            {trip.status === 'confirmed' ? (
              <Link to={'/checkin?pnr=' + trip.pnr} className="rounded-lg bg-cobalt px-5 py-2.5 text-sm font-bold text-white hover:bg-cobaltDark">{t('account.trip.checkin')}</Link>
            ) : (
              <Link to={'/checkin?pnr=' + trip.pnr} className="rounded-lg bg-cobalt px-5 py-2.5 text-sm font-bold text-white hover:bg-cobaltDark">{t('account.trip.boardingPass')}</Link>
            )}
            <button onClick={function () { setModal(true); }} className="rounded-lg border border-line bg-white px-5 py-2.5 text-sm font-semibold text-ink hover:border-cobalt">{t('account.trip.changeSeat')}</button>
            <button onClick={function () { showToast(t('account.trip.comingSoon')); }} className="rounded-lg border border-line bg-white px-5 py-2.5 text-sm font-semibold text-ink hover:border-cobalt">{t('account.trip.invoice')}</button>
          </div>
        ) : null}
        {trip.protection ? (
          <section aria-label={t('account.trip.protectionSection')} className="mt-6 rounded-xl border border-line bg-white p-4">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div className="flex items-center gap-3">
                <span className="flex h-10 w-10 items-center justify-center rounded-lg bg-success/10 text-success"><Icon name="shield" size={20}></Icon></span>
                <div>
                  <h2 className="font-bold text-ink">{t('account.trip.protectionSection')}</h2>
                  <p className="text-sm text-muted">{trip.protection.title || t('coverage.' + trip.protection.coverageType)} · {L.fmtEUR(trip.protection.premium)}{trip.protection.policyNumber ? ' · ' + trip.protection.policyNumber : ''}</p>
                </div>
              </div>
              <Link to="/account/protection" className="text-sm font-semibold text-cobalt hover:underline">{t('account.trip.protectionLink')} →</Link>
            </div>
          </section>
        ) : null}
        <Modal open={modal} onClose={function () { setModal(false); }} title={t('account.trip.comingSoon')}>
          <p className="text-sm text-muted">{t('account.trip.comingSoon.body')}</p>
          <button className="mt-4 w-full rounded-lg bg-cobalt py-2.5 text-sm font-bold text-white" onClick={function () { setModal(false); }}>{t('common.close')}</button>
        </Modal>
      </main>
    </RequireAuth>
  );
}

/* ---------- ProtectionPortalPlaceholder (visual stub for the embed) ---------- */
function ProtectionPortalPlaceholder() {
  const { t } = useLang();
  return (
    <div className="flex flex-col gap-5">
      <div>
        <h2 className="text-xl font-bold tracking-tight text-ink">{t('account.protection.title')}</h2>
        <p className="mt-1 text-sm text-muted">{t('account.protection.placeholderBody')}</p>
      </div>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
        <div className="flex min-h-[160px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-line bg-page/50 p-6 text-center">
          <Icon name="shield" size={24} className="text-muted/60"></Icon>
          <p className="text-sm font-semibold text-ink">{t('account.protection.activePolicies')}</p>
          <p className="flex items-center gap-2 text-sm text-muted"><span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-line border-t-muted"></span>{t('account.protection.loading')}</p>
        </div>
        <div className="flex min-h-[160px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-line bg-page/50 p-6 text-center">
          <Icon name="doc" size={24} className="text-muted/60"></Icon>
          <p className="text-sm font-semibold text-ink">{t('account.protection.claims')}</p>
          <p className="text-sm text-muted">{t('account.protection.claimsNone')}</p>
        </div>
      </div>
      <button disabled className="w-fit cursor-not-allowed rounded-lg bg-cobalt/40 px-6 py-3 text-sm font-bold text-white">
        {t('account.protection.fileClaim')}
      </button>
      <p className="text-xs text-muted">{t('account.protection.explainer')}</p>
    </div>
  );
}

/* ---------- ProtectionPortalEmbed (live Sherpa customer portal) ---------- */
function ProtectionPortalEmbed() {
  const { t } = useLang();
  const session = useSession();
  const [url, setUrl] = useState(null);
  const [error, setError] = useState(false);

  useEffect(function () {
    let on = true;
    setUrl(null); setError(false);
    window.VolaireSherpa.portalSession(session ? session.email : null).then(function (res) {
      if (on) setUrl(res.url);
    }).catch(function () {
      if (on) setError(true);
    });
  }, [session && session.email]);

  if (error) return <ProtectionPortalPlaceholder></ProtectionPortalPlaceholder>;
  if (!url) {
    return (
      <div className="flex min-h-[560px] items-center justify-center" role="status" aria-label={t('account.protection.loading')}>
        <span className="flex items-center gap-2 text-sm text-muted">
          <span className="h-4 w-4 animate-spin rounded-full border-2 border-line border-t-cobalt"></span>{t('account.protection.loading')}
        </span>
      </div>
    );
  }
  return (
    <iframe
      title={t('account.protection.title')}
      src={url}
      className="h-[720px] w-full rounded-lg border-0"
      allow="clipboard-write; camera"
    ></iframe>
  );
}

/* ---------- protection hub — SLOT #2, embedded Sherpa customer portal ---------- */
function AccountProtectionPage() {
  const { t } = useLang();
  const trips = L.loadTrips();
  const linkedPnrs = trips.filter(function (x) { return x.protection; }).map(function (x) { return x.pnr; });
  return (
    <RequireAuth>
      <main className="mx-auto max-w-4xl px-4 pt-6" data-screen-label="Protection hub">
        <AccountNav current="/account/protection"></AccountNav>
        <div className="mt-4"><Breadcrumb items={[{ label: t('nav.account'), to: '/account' }, { label: t('account.protection.title') }]}></Breadcrumb></div>
        <section id="protection-portal-slot" className="mt-4 min-h-[600px] overflow-hidden rounded-xl border border-line bg-white p-2 sm:p-3" data-linked-pnrs={linkedPnrs.join(',')}>
          {/* Volaire provides the chrome (header, nav, account context); the embedded
              Sherpa customer portal provides everything inside this slot — active
              policies, claims, document upload and payout tracking. The session is
              minted server-side (/api/portal-session) and the portal boots from the
              tokens in the iframe URL hash. */}
          <ProtectionPortalEmbed></ProtectionPortalEmbed>
        </section>
      </main>
    </RequireAuth>
  );
}

/* ---------- profile ---------- */
function AccountProfilePage() {
  const { t } = useLang();
  const c = L.MOCK_CUSTOMER;
  const rows = [
    [t('booking.passenger.salutation'), c.salutation],
    [t('booking.passenger.firstName'), c.firstName],
    [t('booking.passenger.lastName'), c.lastName],
    [t('booking.passenger.dateOfBirth'), '17/04/1989'],
    [t('booking.passenger.nationality'), c.nationality],
    [t('booking.passenger.email'), c.email],
    [t('booking.passenger.phone'), c.phone],
    ['Volaire Club', c.loyaltyNumber],
  ];
  return (
    <RequireAuth>
      <main className="mx-auto max-w-3xl px-4 pt-6" data-screen-label="Profile">
        <AccountNav current="/account/profile"></AccountNav>
        <h1 className="mt-4 text-3xl font-bold tracking-tight text-ink">{t('account.profile.title')}</h1>
        <div className="mt-5 rounded-xl border border-line bg-white">
          <dl>
            {rows.map(function (r, i) {
              return (
                <div key={i} className={'flex items-center justify-between gap-4 px-5 py-3.5 ' + (i ? 'border-t border-line' : '')}>
                  <dt className="text-sm text-muted">{r[0]}</dt>
                  <dd className="text-sm font-semibold text-ink">{r[1]}</dd>
                </div>
              );
            })}
          </dl>
        </div>
        <button className="mt-4 rounded-lg border border-line bg-white px-5 py-2.5 text-sm font-semibold text-ink hover:border-cobalt"
          onClick={function () { showToast(t('account.trip.comingSoon')); }}>{t('common.edit')}</button>
      </main>
    </RequireAuth>
  );
}

/* ---------- payment methods ---------- */
function AccountPaymentPage() {
  const { t } = useLang();
  const c = L.MOCK_CUSTOMER;
  return (
    <RequireAuth>
      <main className="mx-auto max-w-3xl px-4 pt-6" data-screen-label="Payment methods">
        <AccountNav current="/account/payment"></AccountNav>
        <h1 className="mt-4 text-3xl font-bold tracking-tight text-ink">{t('account.payment.title')}</h1>
        <div className="mt-5 flex items-center justify-between gap-4 rounded-xl border border-line bg-white p-5">
          <div className="flex items-center gap-4">
            <span className="flex h-11 w-16 items-center justify-center rounded-lg bg-ink text-[11px] font-bold tracking-widest text-white">{c.cardBrand.toUpperCase()}</span>
            <div>
              <p className="font-semibold tabular-nums text-ink">•••• •••• •••• {c.cardLast4}</p>
              <p className="text-sm tabular-nums text-muted">{t('account.payment.expires')} {c.cardExpiry}</p>
            </div>
          </div>
          <button className="text-sm font-medium text-muted hover:text-danger" onClick={function () { showToast(t('account.trip.comingSoon')); }}>{t('common.remove')}</button>
        </div>
        <button className="mt-4 rounded-lg border border-dashed border-line bg-white px-5 py-2.5 text-sm font-semibold text-cobalt hover:border-cobalt"
          onClick={function () { showToast(t('account.trip.comingSoon')); }}>+ {t('account.payment.add')}</button>
      </main>
    </RequireAuth>
  );
}

Object.assign(window, {
  RequireAuth, AccountNav, AccountPage, AccountTripsPage, AccountTripDetailPage,
  ProtectionPortalPlaceholder, ProtectionPortalEmbed, AccountProtectionPage, AccountProfilePage, AccountPaymentPage, ItineraryCard,
});
