/* London Free Guide — First Time page sections.
   Renders from window.LFG_FIRSTTIME. Presentational; the stateful planner
   lives here too. Exported to window, mounted by firsttime-app.jsx. */
const { useState: useFtState, useMemo: useFtMemo } = React;

const FT = window.LFG_FIRSTTIME || { spots: [], itinerary: [], howto: [], overpay: [], mistakes: [], hoods: [] };

/* ---- maps helpers (self-contained, no dependency on saved.jsx internals) ---- */
function ftMapsSearch(s) {
  return "https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent(s.name + " " + s.area + " London");
}
function ftMapsRoute(list) {
  if (!list.length) return "#";
  const pts = list.map((s) => encodeURIComponent(s.name + " " + s.area + " London"));
  if (pts.length === 1) return "https://www.google.com/maps/search/?api=1&query=" + pts[0];
  const dest = pts[pts.length - 1];
  const wp = pts.slice(0, -1).join("%7C");
  return "https://www.google.com/maps/dir/?api=1&destination=" + dest + "&waypoints=" + wp + "&travelmode=walking";
}

/* ---- section header ---- */
function FtHead({ kicker, title, lede, id }) {
  return (
    <div className="ft-sec-head" id={id}>
      <div className="ft-divider"></div>
      {kicker && <span className="ft-kicker">{kicker}</span>}
      <h2 className="ft-h">{title}</h2>
      {lede && <p className="ft-lede">{lede}</p>}
    </div>
  );
}

/* ---- a single canon card (links to its spot page, or to Google Maps) ---- */
function CanonCard({ s, n }) {
  const href = s.spotId ? "Spot.html?id=" + s.spotId : ftMapsSearch(s);
  const external = !s.spotId;
  return (
    <a className="ft-card" href={href} {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}>
      <span className="ft-num">{n}</span>
      <div className="ft-card-body">
        <div className="ft-card-name">{s.name}</div>
        <div className="ft-card-loc"><span className="pin" aria-hidden="true">📍</span>{s.area} · {s.tube}</div>
        <div className="ft-card-blurb">{s.blurb}</div>
        <div>
          <span className="ft-tag">Free</span>
          {s.note && <span className="ft-tag note">{s.note}</span>}
        </div>
        <span className="ft-card-go">{s.spotId ? "Read the guide →" : "Open in Maps ↗"}</span>
      </div>
    </a>
  );
}

function CanonSection() {
  const canon = FT.spots.filter((s) => s.canon);
  return (
    <section className="ft-sec" id="canon">
      <div className="wrap">
        <FtHead
          kicker="the unmissable bit"
          title="The free things every first-timer should do"
          lede="London's best museums, views and markets are free. Not cheap, free. Here is the canon, the lot you should not leave without seeing, none of which costs a penny to walk into."
        />
        <div className="ft-canon">
          {canon.map((s, i) => <CanonCard key={s.id} s={s} n={i + 1} />)}
        </div>
      </div>
    </section>
  );
}

/* ---- a real, walkable free day ---- */
function ItinerarySection() {
  const all = FT.itinerary.flatMap((b) => b.stops);
  return (
    <section className="ft-sec" id="freeday">
      <div className="wrap">
        <FtHead
          kicker="one perfect day"
          title="A free day out, start to finish"
          lede="A real route you can walk in a day, museum to river to sunset, and it costs nothing but a few bus taps and your shoe leather."
        />
        <div className="ft-itin">
          {FT.itinerary.map((b) => (
            <div className="ft-itin-block" key={b.part}>
              <span className="ft-itin-dot" aria-hidden="true">{b.icon}</span>
              <div className="ft-itin-part">{b.part}</div>
              <div className="ft-itin-time">{b.time}</div>
              {b.stops.map((st, i) => (
                <div className="ft-stop" key={i}>
                  <div className="ft-stop-name">{st.name}</div>
                  <div className="ft-stop-note">{st.note}</div>
                </div>
              ))}
            </div>
          ))}
        </div>
        <div className="ft-itin-foot">
          <a className="ft-maps" href={ftMapsRoute([
            { name:"British Museum", area:"Bloomsbury" },
            { name:"National Gallery", area:"Trafalgar Square" },
            { name:"Tate Modern", area:"Bankside" },
            { name:"Primrose Hill", area:"Primrose Hill" }
          ])} target="_blank" rel="noopener noreferrer">
            <span aria-hidden="true">🗺</span> Open the whole route in Maps
          </a>
        </div>
      </div>
    </section>
  );
}

/* ---- how London works ---- */
function HowToSection() {
  return (
    <section className="ft-sec" id="howitworks">
      <div className="wrap">
        <FtHead
          kicker="don't panic"
          title="How London actually works"
          lede="Three things that save every first-timer money and stress. Learn these on the train in from the airport and you will look like a local by lunch."
        />
        <div className="ft-grid3">
          {FT.howto.map((c) => (
            <div className="ft-howcard" key={c.t}>
              <h3>{c.t}</h3>
              <p>{c.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---- what's free vs what tourists overpay for ---- */
function OverpaySection() {
  return (
    <section className="ft-sec" id="ripoffs">
      <div className="wrap">
        <FtHead
          kicker="keep your money"
          title="What tourists overpay for"
          lede="For nearly everything they will try to sell you at the airport and on the strip, there is a free version that is honestly better. Here is the swap."
        />
        <div className="ft-overpay">
          {FT.overpay.map((r, i) => (
            <div className="ft-op-row" key={i}>
              <div className="ft-op-paid">
                <div className="ft-op-label">Skip</div>
                <span className="ft-op-name">{r.paid}</span>
                <div className="ft-op-price">{r.price}</div>
              </div>
              <div className="ft-op-arrow" aria-hidden="true">→</div>
              <div className="ft-op-free">
                <div className="ft-op-label">Do this instead</div>
                <div className="ft-op-name">{r.free}{r.cheap && <span className="ft-op-badge">cheap not free</span>}</div>
                <div className="ft-op-why">{r.why}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---- rookie mistakes ---- */
function MistakesSection() {
  return (
    <section className="ft-sec" id="mistakes">
      <div className="wrap">
        <FtHead
          kicker="learn from us"
          title="Don't make these rookie mistakes"
          lede="The little things that mark you out as fresh off the plane. Get them right and the city opens up."
        />
        <div className="ft-mistakes">
          {FT.mistakes.map((m, i) => (
            <div className="ft-mistake" key={i}>
              <span className="ft-x" aria-hidden="true">✕</span>
              <p>{m}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---- neighbourhoods at a glance ---- */
function HoodsSection() {
  return (
    <section className="ft-sec" id="hoods">
      <div className="wrap">
        <FtHead
          kicker="where to start"
          title="The neighbourhoods, at a glance"
          lede="London is a stack of villages that grew into each other. Here is the quick map of where to point yourself, and what each corner is for."
        />
        <div className="ft-hoods">
          {FT.hoods.map((h) => (
            <div className="ft-hood" key={h.name}>
              <h3>{h.name}</h3>
              <p>{h.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ===================== the 3-tap planner ===================== */
const FT_WHERE = [
  { key:"anywhere", label:"Anywhere" },
  { key:"central",  label:"Central" },
  { key:"south",    label:"South" },
  { key:"east",     label:"East" },
  { key:"north",    label:"North" },
  { key:"west",     label:"West" }
];
const FT_VIBE = [
  { key:"culture", label:"Culture" },
  { key:"views",   label:"Parks & views", match:["views","parks"] },
  { key:"markets", label:"Markets & street life", match:["markets"] },
  { key:"walks",   label:"A good walk", match:["walks"] }
];
const FT_LEN = [
  { key:"half", label:"Half a day", n:3 },
  { key:"full", label:"A full day", n:5 }
];

function Planner() {
  const [where, setWhere] = useFtState(null);
  const [vibe, setVibe] = useFtState(null);
  const [len, setLen] = useFtState(null);
  const [plan, setPlan] = useFtState(null);

  const ready = where && vibe && len;

  function build() {
    if (!ready) return;
    const vibeCfg = FT_VIBE.find((v) => v.key === vibe);
    const want = vibeCfg.match || [vibeCfg.key];
    const lenCfg = FT_LEN.find((l) => l.key === len);

    const score = (s) => {
      let pts = 0;
      if (where !== "anywhere" && s.zone === where) pts += 2;
      const hits = s.vibe.filter((t) => want.includes(t)).length;
      pts += hits * 2;
      return pts;
    };
    let pool = FT.spots
      .map((s) => ({ s, sc: score(s) }))
      .filter((x) => x.sc > 0)
      .sort((a, b) => b.sc - a.sc);

    // top up with the canon if the filter was too tight
    if (pool.length < lenCfg.n) {
      const have = new Set(pool.map((x) => x.s.id));
      FT.spots.filter((s) => s.canon && !have.has(s.id)).forEach((s) => pool.push({ s, sc: 0 }));
    }
    const picks = pool.slice(0, lenCfg.n).map((x) => x.s);
    setPlan({ picks, where, vibe, len });
  }

  function reset() { setWhere(null); setVibe(null); setLen(null); setPlan(null); }

  function askBrolly() {
    if (!plan) return;
    const names = plan.picks.map((p) => p.name).join(", ");
    const lenCfg = FT_LEN.find((l) => l.key === plan.len);
    const q = "I have got " + (lenCfg ? lenCfg.label.toLowerCase() : "a day") + " in London. Can you turn these free spots into a good route with timings: " + names + "?";
    window.dispatchEvent(new CustomEvent("lfg-brolly-open", { detail: { ask: q } }));
  }

  const whereLabel = where && FT_WHERE.find((w) => w.key === where).label;

  return (
    <section className="ft-planner-sec" id="planner">
      <div className="wrap">
        <div className="ft-planner">
          <div className="ft-planner-inner">
            <span className="ft-planner-eyebrow">no idea where to start?</span>
            <h2 className="ft-planner-h">Build my free day</h2>
            <p className="ft-planner-sub">Three taps and we will pull a free day out of our spots for you. Tweak it, open it in Maps, or hand it to Brolly to turn into a proper route.</p>

            <div className="ft-q">
              <div className="ft-q-label"><span className="ft-q-n">1</span><span className="ft-q-t">Where do you fancy?</span></div>
              <div className="ft-opts">
                {FT_WHERE.map((w) => (
                  <button key={w.key} className={"ft-opt" + (where === w.key ? " on" : "")} onClick={() => setWhere(w.key)} aria-pressed={where === w.key}>{w.label}</button>
                ))}
              </div>
            </div>

            <div className="ft-q">
              <div className="ft-q-label"><span className="ft-q-n">2</span><span className="ft-q-t">What's the vibe?</span></div>
              <div className="ft-opts">
                {FT_VIBE.map((v) => (
                  <button key={v.key} className={"ft-opt" + (vibe === v.key ? " on" : "")} onClick={() => setVibe(v.key)} aria-pressed={vibe === v.key}>{v.label}</button>
                ))}
              </div>
            </div>

            <div className="ft-q">
              <div className="ft-q-label"><span className="ft-q-n">3</span><span className="ft-q-t">How long have you got?</span></div>
              <div className="ft-opts">
                {FT_LEN.map((l) => (
                  <button key={l.key} className={"ft-opt" + (len === l.key ? " on" : "")} onClick={() => setLen(l.key)} aria-pressed={len === l.key}>{l.label}</button>
                ))}
              </div>
            </div>

            <div className="ft-plan-actions">
              <button className="ft-build" onClick={build} disabled={!ready}>Build my day →</button>
              {(where || vibe || len) && <button className="ft-reset" onClick={reset}>Start over</button>}
            </div>

            {plan && (
              <div className="ft-result">
                <div className="ft-result-head">
                  <div className="ft-result-title">Your <span className="r">free</span> day{whereLabel && plan.where !== "anywhere" ? " in " + whereLabel : ""}</div>
                  <div className="ft-result-meta">{plan.picks.length} stops · all free</div>
                </div>

                {plan.picks.length ? (
                  <React.Fragment>
                    <div className="ft-plan-list">
                      {plan.picks.map((p, i) => (
                        <div className="ft-plan-row" key={p.id}>
                          <span className="ft-plan-rank">{i + 1}</span>
                          <div className="ft-plan-body">
                            <div className="ft-plan-name">{p.name}</div>
                            <div className="ft-plan-loc"><span className="pin" aria-hidden="true">📍</span>{p.area} · {p.tube}</div>
                            <div className="ft-plan-blurb">{p.blurb}</div>
                            <a className="ft-plan-link" href={p.spotId ? "Spot.html?id=" + p.spotId : ftMapsSearch(p)} {...(p.spotId ? {} : { target: "_blank", rel: "noopener noreferrer" })}>{p.spotId ? "Read the guide →" : "Open in Maps ↗"}</a>
                          </div>
                        </div>
                      ))}
                    </div>
                    <div className="ft-result-cta">
                      <a className="ft-rbtn solid" href={ftMapsRoute(plan.picks)} target="_blank" rel="noopener noreferrer"><span aria-hidden="true">🗺</span> Open the route in Maps</a>
                      <button className="ft-rbtn ghost" onClick={askBrolly}><span aria-hidden="true">☔</span> Hand it to Brolly</button>
                    </div>
                  </React.Fragment>
                ) : (
                  <div className="ft-plan-empty">Nothing matched that exactly. Try <a href="#" onClick={(e) => { e.preventDefault(); setWhere("anywhere"); }}>anywhere</a> for the vibe, or just <a href="Home.html">browse everything</a>.</div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---- first-timer questions (accordion, answer-shaped for SEO) ---- */
function FaqSection() {
  const [open, setOpen] = useFtState(0);
  const faqs = FT.faqs || [];
  return (
    <section className="ft-sec" id="faq">
      <div className="wrap">
        <FtHead
          kicker="straight answers"
          title="First-timer questions, answered"
          lede="The things everyone wonders before they come. Short answers, no waffle."
        />
        <div className="ft-faq">
          {faqs.map((f, i) => {
            const isOpen = open === i;
            return (
              <div className={"ft-faq-item" + (isOpen ? " open" : "")} key={i}>
                <button className="ft-faq-q" aria-expanded={isOpen} onClick={() => setOpen(isOpen ? -1 : i)}>
                  <span>{f.q}</span>
                  <span className="ft-faq-ico" aria-hidden="true">{isOpen ? "−" : "+"}</span>
                </button>
                {isOpen && <div className="ft-faq-a">{f.a}</div>}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ---- where to stay (area picks, honest budget notes) ---- */
function PriceBand({ n }) {
  return (
    <span className="ft-price" aria-label={n + " of 3 for price"}>
      {[1, 2, 3].map((i) => <span key={i} className={"ft-pound" + (i <= n ? " on" : "")}>£</span>)}
    </span>
  );
}

function StaySection() {
  const stay = FT.stay || { areas: [], avoid: [], types: [], legend: "" };
  function roomSearch(area) {
    return "https://www.google.com/search?q=" + encodeURIComponent("hotels in " + area + " London");
  }
  return (
    <section className="ft-sec" id="stay">
      <div className="wrap">
        <FtHead
          kicker="rest your head"
          title="Where to stay without overpaying"
          lede="The right base puts the free London on your doorstep and keeps you off pricey taxis. Here is where to book, who each area suits, and a rough idea of the damage."
        />
        <div className="ft-stay-legend">{stay.legend}</div>

        <div className="ft-stay-grid">
          {stay.areas.map((a) => (
            <div className="ft-stay-card" key={a.name}>
              <div className="ft-stay-top">
                <span className="ft-stay-tag">{a.tag}</span>
                <PriceBand n={a.price} />
              </div>
              <h3 className="ft-stay-name">{a.name}</h3>
              <div className="ft-stay-meta"><span className="ft-stay-zone">{a.zone}</span><span className="ft-stay-lines">{a.lines}</span></div>
              <p className="ft-stay-blurb">{a.blurb}</p>
              <div className="ft-stay-near"><span className="pin" aria-hidden="true">📍</span>{a.near}</div>
              <a className="ft-stay-link" href={roomSearch(a.name)} target="_blank" rel="noopener noreferrer">Find a room in {a.name.split(" & ")[0].split(" &")[0]} ↗</a>
            </div>
          ))}
        </div>

        <div className="ft-stay-split">
          <div className="ft-stay-types">
            <h3 className="ft-stay-subh">Hotel, Airbnb or hostel?</h3>
            <div className="ft-stay-typerow">
              {stay.types.map((ty) => (
                <div className="ft-stay-type" key={ty.t}>
                  <div className="ft-stay-type-t">{ty.t}</div>
                  <p>{ty.d}</p>
                </div>
              ))}
            </div>
          </div>
          <div className="ft-stay-avoid">
            <h3 className="ft-stay-subh">Don't overpay to sleep here</h3>
            {stay.avoid.map((av) => (
              <div className="ft-avoid-item" key={av.t}>
                <span className="ft-x" aria-hidden="true">✕</span>
                <div><div className="ft-avoid-t">{av.t}</div><p>{av.d}</p></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---- getting in from the airport ---- */
function AirportSection() {
  const air = FT.airport || { heathrow: [], others: [], dos: [], donts: [], note: "" };
  return (
    <section className="ft-sec" id="airport">
      <div className="wrap">
        <FtHead
          kicker="off the plane"
          title="Getting in from the airport"
          lede="The single easiest place to get fleeced before you have even arrived. Here is the cheapest sensible way in, and what to walk straight past."
        />

        <div className="ft-air-label">From Heathrow, the big three</div>
        <div className="ft-air-grid">
          {air.heathrow.map((o) => (
            <div className={"ft-air-card" + (o.best ? " best" : "")} key={o.name}>
              {o.best && <span className="ft-air-flag">Our pick for value</span>}
              <span className="ft-air-tag">{o.tag}</span>
              <h3 className="ft-air-name">{o.name}</h3>
              <div className="ft-air-stats">
                <span className="ft-air-price">{o.price}</span>
                <span className="ft-air-time">{o.time}</span>
              </div>
              <p className="ft-air-d">{o.d}</p>
            </div>
          ))}
        </div>

        <div className="ft-air-label">From the other airports</div>
        <div className="ft-air-others">
          {air.others.map((o) => (
            <div className="ft-air-row" key={o.airport}>
              <div className="ft-air-port">{o.airport}</div>
              <div className="ft-air-route">
                <div className="ft-air-cheap"><span className="ft-air-take">Take</span> {o.cheap} <span className="ft-air-from">{o.price}</span></div>
                <div className="ft-air-to"><span aria-hidden="true">→</span> {o.to}</div>
                <div className="ft-air-skip">{o.skip}</div>
              </div>
            </div>
          ))}
        </div>
        <div className="ft-air-note">{air.note}</div>

        <div className="ft-air-dd">
          <div className="ft-air-do">
            <h3 className="ft-air-ddh">Do</h3>
            {air.dos.map((d, i) => (
              <div className="ft-dd-item" key={i}><span className="ft-tick" aria-hidden="true">✓</span><p>{d}</p></div>
            ))}
          </div>
          <div className="ft-air-dont">
            <h3 className="ft-air-ddh">Don't</h3>
            {air.donts.map((d, i) => (
              <div className="ft-dd-item" key={i}><span className="ft-x" aria-hidden="true">✕</span><p>{d}</p></div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  FtHead, CanonSection, ItinerarySection, HowToSection, AirportSection,
  OverpaySection, MistakesSection, HoodsSection, StaySection, FaqSection, Planner
});
