/* London Free Guide — First Time page app.
   The "Start Here" hero + jump nav + section composition + tweaks.
   Editorial sits up top (public, rankable); the planner is the interactive
   layer. Reuses the shared Nav / Band / Footer / Brolly. */
const { useEffect: useFtEffect } = React;

const FT_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#E63B2E",
  "showPlanner": true,
  "showAirport": true,
  "showRipoffs": true,
  "showHoods": true,
  "showStay": true,
  "showFaq": true
}/*EDITMODE-END*/;

/* ItemList JSON-LD for the free canon — the GEO/SEO engine.
   Prototype demo of what the build should emit server-side. */
function FirstTimeSchema() {
  useFtEffect(() => {
    const canon = (window.LFG_FIRSTTIME ? window.LFG_FIRSTTIME.spots : []).filter((s) => s.canon);
    const data = {
      "@context": "https://schema.org",
      "@type": "ItemList",
      name: "Free things to do in London for first-timers",
      description: "The unmissable free things to do on a first visit to London — museums, views, parks and markets, all free to enter.",
      url: window.location.href,
      numberOfItems: canon.length,
      itemListElement: canon.map((s, i) => ({
        "@type": "ListItem",
        position: i + 1,
        item: {
          "@type": "TouristAttraction",
          name: s.name,
          description: s.blurb,
          isAccessibleForFree: true,
          address: { "@type": "PostalAddress", addressLocality: s.area, addressRegion: "London", addressCountry: "GB" }
        }
      }))
    };
    let el = document.getElementById("ft-jsonld");
    if (!el) { el = document.createElement("script"); el.type = "application/ld+json"; el.id = "ft-jsonld"; document.head.appendChild(el); }
    el.textContent = JSON.stringify(data, null, 2);

    const faqs = (window.LFG_FIRSTTIME ? window.LFG_FIRSTTIME.faqs : []) || [];
    if (faqs.length) {
      const faqData = {
        "@context": "https://schema.org",
        "@type": "FAQPage",
        mainEntity: faqs.map((f) => ({
          "@type": "Question",
          name: f.q,
          acceptedAnswer: { "@type": "Answer", text: f.a }
        }))
      };
      let fel = document.getElementById("ft-faq-jsonld");
      if (!fel) { fel = document.createElement("script"); fel.type = "application/ld+json"; fel.id = "ft-faq-jsonld"; document.head.appendChild(fel); }
      fel.textContent = JSON.stringify(faqData, null, 2);
    }
  }, []);
  return null;
}

function smoothTo(id) {
  const el = document.getElementById(id);
  if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.pageYOffset - 96, behavior: "smooth" });
}

function FtHero() {
  return (
    <section className="ft-hero">
      <div className="wrap">
        <div className="ft-hero-inner">
          <div className="ft-hero-l">
            <span className="ft-eyebrow">first time in London?</span>
            <h1 className="ft-title">DO IT ALL FOR <span className="r">FREE</span></h1>
          </div>
          <div className="ft-hero-r">
            <p className="ft-sub">Whether you are here for a weekend or you have just moved in, the best of London costs nothing. World-class museums, rooftop views, royal parks and proper markets, all free. Here is how to do it like a local, not a tourist.</p>
            <div className="ft-hero-cta">
              <a className="ft-btn-lg solid" href="#planner" onClick={(e) => { e.preventDefault(); smoothTo("planner"); }}>Build my free day →</a>
              <a className="ft-btn-lg ghost" href="#canon" onClick={(e) => { e.preventDefault(); smoothTo("canon"); }}>The must-dos</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

const FT_JUMP = [
  { id:"canon", label:"The must-dos" },
  { id:"freeday", label:"A free day" },
  { id:"howitworks", label:"How it works" },
  { id:"airport", label:"From the airport" },
  { id:"ripoffs", label:"Don't get done" },
  { id:"hoods", label:"The areas" },
  { id:"stay", label:"Where to stay" },
  { id:"faq", label:"Questions" },
  { id:"planner", label:"Plan my day" }
];
function FtJump({ show }) {
  const items = FT_JUMP.filter((j) => show[j.id] !== false);
  return (
    <nav className="ft-jump" aria-label="On this page">
      <div className="wrap ft-jump-row">
        {items.map((j) => (
          <a key={j.id} href={"#" + j.id} onClick={(e) => { e.preventDefault(); smoothTo(j.id); }}>{j.label}</a>
        ))}
      </div>
    </nav>
  );
}

/* "London today" bar — today's weather on the left (Open-Meteo via
   window.LFGWeather) + rotating items on the right. Tube status leads (live
   from TfL via window.LFGTube), then the first-timer reassurance facts. All
   self-updating; failed items are simply dropped. Renders via window.NowBar. */
function LondonNow() {
  const [fc, setFc] = React.useState([]);
  const [tube, setTube] = React.useState(null);
  React.useEffect(() => {
    let live = true;
    if (window.LFGWeather) window.LFGWeather.london().then((d) => {
      if (live && d && d.length) setFc(d.slice(0, 3).map((x) => ({ label: window.LFGNow.label(x.date), code: x.code, t: x.t })));
    }).catch(() => {});
    if (window.LFGTube) window.LFGTube.status().then((s) => { if (live) setTube(s); }).catch(() => {});
    return () => { live = false; };
  }, []);
  if (!window.NowBar) return null;
  const NB = window.NowBar;
  const items = [];
  if (tube) items.push(NB.tube(tube));
  items.push(<span>Single tube <b>£3</b> · daily cap <b>£8.90</b></span>);
  items.push(<span>Tap any bank card, <b>no Oyster</b> needed</span>);
  items.push(<span>Tap water is <b>free</b> everywhere</span>);
  return <NowBar forecast={fc} items={items} tickKey={tube ? "t" : "n"} />;
}

function FirstTimeApp() {
  const [t, setTweak] = useTweaks(FT_TWEAK_DEFAULTS);

  useFtEffect(() => {
    document.documentElement.style.setProperty("--lfg-accent", t.accent);
  }, [t.accent]);

  const jumpShow = {
    ripoffs: t.showRipoffs,
    airport: t.showAirport,
    hoods: t.showHoods,
    stay: t.showStay,
    faq: t.showFaq,
    planner: t.showPlanner
  };

  return (
    <React.Fragment>
      <FirstTimeSchema />
      <Nav />
      <LondonNow />
      <FtHero />
      <FtJump show={jumpShow} />
      <main>
        <CanonSection />
        <ItinerarySection />
        <HowToSection />
        {t.showAirport && <AirportSection />}
        {t.showRipoffs && <OverpaySection />}
        {t.showHoods && <HoodsSection />}
        {t.showStay && <StaySection />}
        {t.showFaq && <FaqSection />}
        {t.showPlanner && <Planner />}
        <div className="wrap ft-foot-nav">
          <a className="ft-back-link" href="Home.html"><span aria-hidden="true">←</span> Back to Explore</a>
        </div>
      </main>
      <Band />
      <Footer />
      <GuideAgent />

      <TweaksPanel>
        <TweakSection label="Brand accent" />
        <TweakColor label="Accent colour" value={t.accent}
          options={["#E63B2E", "#FF6A1A", "#1F8A5B", "#2A6FDB"]}
          onChange={(v) => setTweak("accent", v)} />

        <TweakSection label="Sections" />
        <TweakToggle label="The day planner" value={t.showPlanner}
          onChange={(v) => setTweak("showPlanner", v)} />
        <TweakToggle label="Airport routes" value={t.showAirport}
          onChange={(v) => setTweak("showAirport", v)} />
        <TweakToggle label="Rip-off swaps" value={t.showRipoffs}
          onChange={(v) => setTweak("showRipoffs", v)} />
        <TweakToggle label="Neighbourhoods" value={t.showHoods}
          onChange={(v) => setTweak("showHoods", v)} />
        <TweakToggle label="Where to stay" value={t.showStay}
          onChange={(v) => setTweak("showStay", v)} />
        <TweakToggle label="Questions (FAQ)" value={t.showFaq}
          onChange={(v) => setTweak("showFaq", v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<FirstTimeApp />);
