// Info page — trip-essential reference info pulled from confirmation PDFs.
// Source data: info-data.js (window.INFO).

function telHref(phone) {
  if (!phone) return null;
  return `tel:${phone.replace(/[^+0-9]/g, '')}`;
}

function mapsHref(addr, name) {
  if (!addr && !name) return null;
  const q = encodeURIComponent(addr ? `${name || ''} ${addr}`.trim() : name);
  return `https://www.google.com/maps/search/?api=1&query=${q}`;
}

function useInfoAuthState() {
  const [auth, setAuth] = React.useState(() => {
    if (window.RoadtripAuth && window.RoadtripAuth.getState) return window.RoadtripAuth.getState();
    return { ready: true, user: null, error: null };
  });
  React.useEffect(() => {
    if (!window.RoadtripAuth || !window.RoadtripAuth.subscribe) return;
    return window.RoadtripAuth.subscribe(setAuth);
  }, []);
  return auth;
}

const CONTACT_OVERRIDES_KEY = "roadtrip-contact-overrides-v1";
const ADDABLE_CONTACT_LABELS = new Set(["Family back home", "Family doctor"]);

function readContactOverrides() {
  try { return JSON.parse(localStorage.getItem(CONTACT_OVERRIDES_KEY) || "{}"); }
  catch { return {}; }
}

function writeContactOverrides(next) {
  try { localStorage.setItem(CONTACT_OVERRIDES_KEY, JSON.stringify(next)); } catch {}
}

function InfoRow({ label, value, mono, link }) {
  if (!value) return null;
  return (
    <div className="info-row">
      <div className="ir-key">{label}</div>
      <div className={`ir-val ${mono ? 'mono' : ''}`}>
        {link ? <a href={link} target="_blank" rel="noopener">{value}</a> : value}
      </div>
    </div>
  );
}

function InfoActions({ phone, web, addr, name }) {
  return (
    <div className="info-actions">
      {phone && <a className="phone" href={telHref(phone)}>☏ Call</a>}
      {web && <a className="web" href={web} target="_blank" rel="noopener">↗ Website</a>}
      {(addr || name) && <a className="map" href={mapsHref(addr, name)} target="_blank" rel="noopener">◉ Maps</a>}
    </div>
  );
}

function InfoCard({ dayBadge, name, meta, children, defaultOpen }) {
  const [open, setOpen] = React.useState(!!defaultOpen);
  return (
    <div className={`info-card ${open ? 'open' : ''}`}>
      <div className="info-card-head" onClick={() => setOpen(!open)}>
        {dayBadge && <div className="ic-day">{dayBadge}</div>}
        <div className="ic-body">
          <div className="ic-name">{name}</div>
          {meta && <div className="ic-meta">{meta}</div>}
        </div>
        <div className="ic-caret">⌄</div>
      </div>
      {open && <div className="info-card-body">{children}</div>}
    </div>
  );
}

function FlightCardInfo({ f }) {
  return (
    <InfoCard
      name={f.label}
      meta={`${f.flightNum} · ${f.depart.time} → ${f.arrive.time}`}
    >
      <InfoRow label="Airline"   value={f.airline} />
      <InfoRow label="Flight #"  value={f.flightNum} mono />
      <InfoRow label="Conf #"    value={f.conf} mono />
      <InfoRow label="Depart"    value={`${f.depart.code} · ${f.depart.date} · ${f.depart.time}`} />
      <InfoRow label="Arrive"    value={`${f.arrive.code} · ${f.arrive.date} · ${f.arrive.time}`} />
      <InfoRow label="Duration"  value={f.duration} />
      <InfoRow label="Aircraft"  value={f.aircraft} />
      <InfoRow label="Fare"      value={f.fareClass} />
      <InfoRow label="Seats"     value={f.seats} mono />
      <InfoActions phone={f.checkInPhone} web={f.url} />
    </InfoCard>
  );
}

function CarCardInfo({ c }) {
  return (
    <InfoCard
      name={c.company}
      meta={`${c.model} · ${c.pickup.location} → ${c.dropoff.location}`}
    >
      <InfoRow label="Model"        value={c.model} />
      <InfoRow label="Costco Conf"  value={c.confCostco} mono />
      <InfoRow label="Avis Conf"    value={c.confAvis} mono />
      <InfoRow label="Costco #"     value={c.costcoMember} mono />
      <InfoRow label="Pickup"       value={`${c.pickup.date} · ${c.pickup.time}`} />
      <InfoRow label="Pickup loc"   value={`${c.pickup.location} · ${c.pickup.addr}`} />
      <InfoRow label="Pickup ph"    value={c.pickup.phone} mono />
      <InfoRow label="Drop-off"     value={`${c.dropoff.date} · ${c.dropoff.time}`} />
      <InfoRow label="Drop-off loc" value={`${c.dropoff.location} · ${c.dropoff.addr}`} />
      <InfoRow label="Drop-off ph"  value={c.dropoff.phone} mono />
      <InfoRow label="Total Due"    value={c.totalDue} mono />
      <InfoRow label="Help · Pre"   value={c.helpBeforeTrip} mono />
      <InfoRow label="Help · On"    value={c.helpDuringTrip} mono />
      {c.notes && <InfoRow label="Notes" value={c.notes} />}
      <InfoActions
        phone={c.pickup.phone}
        addr={c.pickup.addr}
        name={c.pickup.location}
      />
    </InfoCard>
  );
}

function HotelCardInfo({ h }) {
  return (
    <InfoCard
      dayBadge={`D${h.day}`}
      name={h.name}
      meta={`${h.nights} night${h.nights > 1 ? 's' : ''} · ${h.rooms} room${h.rooms > 1 ? 's' : ''} · ${h.city}`}
    >
      <InfoRow label="Address"    value={h.addr} />
      <InfoRow label="Phone"      value={h.phone} mono />
      <InfoRow label="Conf #"     value={h.conf} mono />
      <InfoRow label="Booked via" value={h.bookedThrough} />
      <InfoRow label="Check in"   value={h.checkIn} />
      <InfoRow label="Check out"  value={h.checkOut} />
      <InfoRow label="Rooms"      value={`${h.rooms} (${h.occupancy})`} />
      <InfoRow label="Room type"  value={h.roomType} />
      <InfoRow label="Beds"       value={h.bedType} />
      <InfoRow label="Rate"       value={h.rate} mono />
      <InfoRow label="Total"      value={h.total} mono />
      <InfoRow label="Cancel"     value={h.cancel} />
      {h.notes && <InfoRow label="Notes" value={h.notes} />}
      <InfoActions phone={h.phone} web={h.web} addr={h.addr} name={h.name} />
    </InfoCard>
  );
}

function ActivityCardInfo({ a }) {
  return (
    <InfoCard
      dayBadge={`D${a.day}`}
      name={a.name}
      meta={`${a.date} · ${a.time}`}
    >
      <InfoRow label="Address"    value={a.addr} />
      <InfoRow label="Phone"      value={a.phone} mono />
      <InfoRow label="Conf"       value={a.conf} mono />
      <InfoRow label="Booked via" value={a.bookedThrough} />
      <InfoRow label="Tickets"    value={a.tickets} />
      <InfoRow label="Total"      value={a.total} mono />
      <InfoRow label="Auth"       value={a.auth} mono />
      {a.notes && <InfoRow label="Notes" value={a.notes} />}
      <InfoActions phone={a.phone} web={a.web} addr={a.addr} name={a.name} />
    </InfoCard>
  );
}

function ContactRow({ c, canEdit, onSavePhone }) {
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState("");
  const canAddPhone = !c.phone && ADDABLE_CONTACT_LABELS.has(c.label);

  const submit = (e) => {
    e.preventDefault();
    const value = draft.trim();
    if (!value) return;
    onSavePhone(c.label, value);
    setDraft("");
    setEditing(false);
  };

  return (
    <div className="contact-row">
      <div className="cr-body">
        <div className="cr-label">{c.label}</div>
        {c.note && <div className="cr-note">{c.note}</div>}
        {editing && (
          <form className="cr-add-form" onSubmit={submit}>
            <input
              type="tel"
              value={draft}
              onChange={(e) => setDraft(e.target.value)}
              placeholder="Enter phone number"
              autoFocus
            />
            <button type="button" className="cr-add-btn subtle" onClick={() => setEditing(false)}>Cancel</button>
            <button type="submit" className="cr-add-btn">Save</button>
          </form>
        )}
      </div>
      {c.phone ? (
        <a className="cr-call" href={telHref(c.phone)}>{c.phone}</a>
      ) : canAddPhone && canEdit ? (
        <button className="cr-add-btn" onClick={() => setEditing(true)}>Add</button>
      ) : canAddPhone ? (
        <span className="cr-call empty">Sign in to add</span>
      ) : (
        <span className="cr-call empty">— add —</span>
      )}
    </div>
  );
}

// ----- Search filter -----
function matchesSearch(card, q) {
  if (!q) return true;
  const text = JSON.stringify(card).toLowerCase();
  return text.includes(q.toLowerCase());
}

function InfoPage() {
  const INFO = window.INFO;
  const auth = useInfoAuthState();
  const [q, setQ] = React.useState('');
  const [busyAuth, setBusyAuth] = React.useState(false);
  const [contactOverrides, setContactOverrides] = React.useState(() => readContactOverrides());

  const contactsWithOverrides = React.useMemo(() => (
    INFO.emergencyContacts.map((c) => ({
      ...c,
      phone: (contactOverrides[c.label] || c.phone || "").trim(),
    }))
  ), [INFO.emergencyContacts, contactOverrides]);

  const flights     = INFO.flights.filter(f => matchesSearch(f, q));
  const showCar     = matchesSearch(INFO.rentalCar, q);
  const hotels      = INFO.hotels.filter(h => matchesSearch(h, q));
  const activities  = INFO.activities.filter(a => matchesSearch(a, q));
  const contacts    = contactsWithOverrides.filter(c => matchesSearch(c, q));

  const signIn = async () => {
    if (!window.RoadtripAuth || !window.RoadtripAuth.signIn) return;
    setBusyAuth(true);
    try { await window.RoadtripAuth.signIn(); } catch (_) {}
    finally { setBusyAuth(false); }
  };

  const signOut = async () => {
    if (!window.RoadtripAuth || !window.RoadtripAuth.signOut) return;
    setBusyAuth(true);
    try { await window.RoadtripAuth.signOut(); } catch (_) {}
    finally { setBusyAuth(false); }
  };

  const saveContactPhone = (label, phone) => {
    if (!auth.user) return;
    setContactOverrides((prev) => {
      const next = { ...prev, [label]: phone };
      writeContactOverrides(next);
      return next;
    });
  };

  const Section = ({ title, children, hide }) => {
    if (hide) return null;
    return (
      <div className="info-section">
        <div className="is-head">
          <span className="is-title">{title}</span>
          <span className="is-bar" />
        </div>
        {children}
      </div>
    );
  };

  return (
    <>
      {window.PageHeader && <window.PageHeader title="Trip Info" />}
      <section id="info" data-screen-label="Info">
      <div className="info-auth">
        <div className="info-auth-text">
          {auth.user
            ? `Signed in as ${auth.user.email || auth.user.displayName || "user"}`
            : "Sign in here to enable all editing across the app."}
        </div>
        <button
          className="info-auth-btn"
          onClick={auth.user ? signOut : signIn}
          disabled={busyAuth}
        >
          {busyAuth ? "Please wait..." : (auth.user ? "Sign out" : "Sign in")}
        </button>
      </div>
      {auth.error && (
        <div className="info-auth-error">{auth.error}</div>
      )}
      <div className="page-head no-safe">
        <h1 className="ph-title">Everything you need</h1>
        <p className="ph-sub">Confirmations, addresses, room counts, who-to-call. Searchable.</p>
      </div>

      <div className="info-search">
        <input
          type="search"
          value={q}
          onChange={e => setQ(e.target.value)}
          placeholder="Search hotels, flights, conf #, addresses…"
        />
      </div>

      <Section title="Flights" hide={flights.length === 0}>
        {flights.map(f => <FlightCardInfo key={f.id} f={f} />)}
      </Section>

      <Section title="Rental Car" hide={!showCar}>
        <CarCardInfo c={INFO.rentalCar} />
      </Section>

      <Section title="Hotels" hide={hotels.length === 0}>
        {hotels.map(h => <HotelCardInfo key={h.id} h={h} />)}
      </Section>

      <Section title="Activities & Tours" hide={activities.length === 0}>
        {activities.map(a => <ActivityCardInfo key={a.id} a={a} />)}
      </Section>

      <Section title="Emergency Contacts" hide={contacts.length === 0}>
        {contacts.map((c, i) => (
          <ContactRow
            key={i}
            c={c}
            canEdit={!!auth.user}
            onSavePhone={saveContactPhone}
          />
        ))}
      </Section>

      {flights.length === 0 && !showCar && hotels.length === 0 && activities.length === 0 && contacts.length === 0 && (
        <div className="info-section">
          <div style={{textAlign:'center', padding:'40px 20px', color:'var(--ink-muted)'}}>
            No matches for "{q}"
          </div>
        </div>
      )}
    </section>
    </>
  );
}

window.InfoPage = InfoPage;
