// ============ Sections - brand-aware (reads COPY from window.COPY) ============

const Heading = ({ head, center }) => (
  <div className="sec-head" style={center ? { textAlign: "center", margin: "0 auto 56px" } : undefined}>
    {head.eyebrow && <div className="eyebrow sec-head__eyebrow">{head.eyebrow}</div>}
    <h2 className="display sec-head__title">
      {head.title.map((l, i) => <React.Fragment key={i}>{l}{i < head.title.length - 1 && <br/>}</React.Fragment>)}
    </h2>
    {head.lead && <p className="sec-head__lead">{head.lead}</p>}
  </div>
);

const Hero = ({ variant = 1 }) => {
  const c = window.COPY.hero;

  const Eyebrow = () => (
    <div className="hero__eyebrow">
      <span className="hero__eyebrow__dot"></span><span>{c.eyebrow}</span>
    </div>
  );
  const Title = () => (
    <h1 className="display hero__title">
      {c.title[0]}<br/><em>{c.title[1]}</em><br/>{c.title[2]}
    </h1>
  );
  const Ctas = () => (
    <div className="hero__ctas">
      <a className="btn btn--primary btn--lg" href={(window.COPY && window.COPY.appHref) || "app.html"}>{c.ctaPrimary} <Icon name="arrow-right" size={16}/></a>
      <a className="btn btn--ghost btn--lg" href="#examples">{c.ctaSecondary}</a>
    </div>
  );
  const Meta = () => (
    <div className="hero__meta">
      {c.meta.map((m, i) => <div key={i} className="hero__meta__item"><Icon name="check" size={15}/> {m.t}</div>)}
    </div>
  );

  // V1 - Split: copy left, compare right (default)
  if (variant === 1) {
    return (
      <section className="hero">
        <div className="container hero__grid">
          <div>
            <Eyebrow/>
            <Title/>
            <p className="lead hero__lead">{c.lead}</p>
            <Ctas/>
            <Meta/>
          </div>
          <div><Compare before={IMG.heroBefore} after={IMG.heroAfter}/></div>
        </div>
      </section>
    );
  }

  // V2 - Centered editorial: big headline, compare underneath full-width
  if (variant === 2) {
    return (
      <section className="hero" style={{ paddingTop: 96 }}>
        <div className="container" style={{ textAlign: "center" }}>
          <div style={{ display: "flex", justifyContent: "center", marginBottom: 24 }}><Eyebrow/></div>
          <h1 className="display hero__title" style={{ fontSize: "clamp(56px, 7.5vw, 112px)", maxWidth: "16ch", margin: "0 auto" }}>
            {c.title[0]} <em>{c.title[1]}</em> {c.title[2]}
          </h1>
          <p className="lead hero__lead" style={{ margin: "28px auto 0" }}>{c.lead}</p>
          <div style={{ display: "flex", justifyContent: "center", marginTop: 36 }}><Ctas/></div>
          <div style={{ display: "flex", justifyContent: "center", marginTop: 24 }}><Meta/></div>
          <div style={{ marginTop: 64, maxWidth: 1040, margin: "64px auto 0" }}>
            <Compare before={IMG.heroBefore} after={IMG.heroAfter}/>
          </div>
        </div>
      </section>
    );
  }

  // V3 - Stacked cards: compare on the left edge, card-like copy on right
  return (
    <section className="hero">
      <div className="container hero__grid" style={{ gridTemplateColumns: "1fr 0.95fr" }}>
        <div><Compare before={IMG.heroBefore} after={IMG.heroAfter}/></div>
        <div>
          <Eyebrow/>
          <Title/>
          <p className="lead hero__lead">{c.lead}</p>
          <Ctas/>
          <Meta/>
        </div>
      </div>
    </section>
  );
};

const Trust = () => (
  <section className="section--tight">
    <div className="container">
      <div className="trust">
        {window.COPY.trust.map((t, i) => (
          <div className="trust__item" key={i}>
            <div className="trust__num">{t.num}</div>
            <div className="trust__lbl">{t.lbl}</div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

const Steps = () => (
  <section className="section" id="how">
    <div className="container">
      <Heading head={window.COPY.stepsHead}/>
      <div className="steps">
        {window.COPY.steps.map((s, i) => (
          <div className="step" key={i}>
            <div className="step__num">{s.no}</div>
            <div className="step__ill"><img src={s.img} alt=""/></div>
            <h3 className="step__title">{s.title}</h3>
            <p className="step__body">{s.body}</p>
          </div>
        ))}
      </div>
    </div>
  </section>
);

const Gallery = () => (
  <section className="section" id="examples">
    <div className="container">
      <Heading head={window.COPY.galleryHead}/>
      <div className="gallery">
        {window.COPY.gallery.map((g, i) => (
          <div className="gcard" key={i}>
            <div className="gcard__pair">
              <div className="gcard__half"><span className="gcard__tag">Before</span><img src={g.before} alt=""/></div>
              <div className="gcard__half"><span className="gcard__tag gcard__tag--after">After</span><img src={g.after} alt=""/></div>
            </div>
            <div className="gcard__foot">
              <div className="gcard__foot__l">{g.name}</div>
              <div className="gcard__foot__r">{g.style}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// Styles section now lives at #styles (was misclaiming #features
// which made the footer's Features and Styles links scroll to the
// same place).
const Styles = () => (
  <section className="section" id="styles">
    <div className="container">
      <Heading head={window.COPY.stylesHead}/>
      <div className="styles-grid">
        {window.COPY.styles.map((s, i) => (
          <div className="style-card" key={i}>
            <img src={s.img} alt={s.name}/>
            <div className="style-card__shade"></div>
            <div className="style-card__label">{s.name}</div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// Features section claims #features for the footer link.
const Features = () => (
  <section className="section" id="features">
    <div className="container">
      <Heading head={window.COPY.featuresHead}/>
      <div className="features">
        {window.COPY.features.map((f, i) => (
          <div className="feature" key={i}>
            <div className="feature__icon"><Icon name={f.icon} size={22}/></div>
            <h3 className="feature__title">{f.title}</h3>
            <p className="feature__body">{f.body}</p>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// Room types: new section listing every supported room. Footer's
// "Room types" link previously scrolled to #how (the steps section)
// because there was no real rooms section to link to. The bullet
// dot is a single visual anchor we control - the icon library
// doesn't have furniture pictograms and a missing icon would leave
// 12 inconsistent tiles.
const RoomTypes = () => (
  <section className="section" id="rooms">
    <div className="container">
      <Heading head={window.COPY.roomsHead}/>
      <div className="rooms-grid">
        {window.COPY.rooms.map((r, i) => (
          <div className="room-tile" key={i}>
            <span className="room-tile__dot"/>
            <span className="room-tile__name">{r.name}</span>
          </div>
        ))}
      </div>
    </div>
  </section>
);

const LogoStrip = () => (
  <section className="section--tight">
    <div className="container">
      <div className="eyebrow" style={{ textAlign: "center", marginBottom: 20 }}>{window.COPY.logosHead}</div>
      <div className="logostrip">
        {window.COPY.logos.map((n, i) => (
          <div key={i} className={i % 2 ? "logostrip__logo logostrip__logo--mono" : "logostrip__logo"}>{n}</div>
        ))}
      </div>
    </div>
  </section>
);

const Testimonials = () => (
  <section className="section">
    <div className="container">
      <Heading head={window.COPY.testimonialsHead}/>
      <div className="testimonials">
        {window.COPY.testimonials.map((t, i) => (
          <div className="tcard" key={i}>
            <div className="tcard__stars">
              {Array.from({ length: t.stars }).map((_, j) => <Icon key={j} name="star" size={14}/>)}
            </div>
            <div className="tcard__quote">"{t.quote}"</div>
            <div className="tcard__author">
              <div className="tcard__avatar">{t.initial}</div>
              <div>
                <div className="tcard__name">{t.name}</div>
                <div className="tcard__role">{t.role}</div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

const Pricing = () => (
  <section className="section" id="pricing">
    <div className="container">
      <Heading head={window.COPY.pricingHead}/>
      <div className="pricing">
        {window.COPY.plans.map((p, i) => (
          <div className={`plan ${p.featured ? "plan--featured" : ""}`} key={i}>
            {p.featured && <div className="plan__badge">{p.tag}</div>}
            <div className="plan__name">{p.name}</div>
            <div className="plan__tag">{p.tag}</div>
            <div className="plan__price">{p.price}</div>
            <div className="plan__per">{p.per}</div>
            <ul className="plan__feats">
              {p.feats.map((f, j) => <li className="plan__feat" key={j}><Icon name="check" size={14}/> {f}</li>)}
            </ul>
            <div className="plan__cta">
              <a href={(window.COPY && window.COPY.appHref) || "app.html"} className={p.featured ? "btn btn--primary" : "btn btn--ghost"}>{p.cta}</a>
            </div>
          </div>
        ))}
      </div>
      <p style={{ textAlign: "center", marginTop: 32, fontSize: 13, color: "var(--c-ink-3)" }}>{window.COPY.pricingFoot}</p>
    </div>
  </section>
);

const Faq = () => {
  const [open, setOpen] = React.useState(0);
  return (
    <section className="section" id="faq">
      <div className="container">
        <Heading head={window.COPY.faqHead} center/>
        <div className="faq">
          {window.COPY.faqs.map((f, i) => (
            <FaqItem key={i} {...f} open={open === i} onToggle={() => setOpen(open === i ? -1 : i)}/>
          ))}
        </div>
      </div>
    </section>
  );
};

const CtaBlock = () => {
  const c = window.COPY.ctaHead;
  return (
    <section className="section--tight">
      <div className="container">
        <div className="cta-block">
          <div className="cta-block__bg"></div>
          <h2 className="cta-block__title">
            {c.title.map((l, i) => <React.Fragment key={i}>{l}{i < c.title.length - 1 && <br/>}</React.Fragment>)}
          </h2>
          <p className="cta-block__lead">{c.lead}</p>
          <a href={(window.COPY && window.COPY.appHref) || "app.html"} className="btn btn--primary btn--lg">{c.cta} <Icon name="arrow-right" size={16}/></a>
        </div>
      </div>
    </section>
  );
};

const Footer = () => {
  const f = window.COPY.footer;
  // Each link is now an object: { label, href } where href can be null to
  // skip rendering. We tolerate the legacy string-array shape too (with a
  // small label->href dictionary fallback) so this doesn't break if older
  // copy slips back in.
  const lang = window.APP_LANG || "en";
  const legalUrls = lang === "lt" ? {
    "Privatumas": "/privacy-lt.html",
    "Sąlygos": "/terms-lt.html",
    "Slapukai": "/privacy-lt.html#cookies",
    "Kontaktai": "mailto:support@restager.app",
  } : {
    "Privacy": "/privacy.html",
    "Terms": "/terms.html",
    "Cookies": "/privacy.html#cookies",
    "Contact": "mailto:support@restager.app",
  };
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer__grid">
          <div className="footer__brand">
            <div className="footer__brand__name">{window.COPY.brandName}</div>
            <div className="footer__brand__desc">{f.blurb}</div>
          </div>
          {f.cols.map((c, i) => (
            <div className="footer__col" key={i}>
              <h4>{c.h}</h4>
              <ul>{c.links
                .filter((l) => (typeof l === "string" ? true : l.href != null))
                .map((l, j) => {
                  const label = typeof l === "string" ? l : l.label;
                  const href = typeof l === "string" ? (legalUrls[l] || "#") : l.href;
                  return <li key={j}><a href={href}>{label}</a></li>;
                })}</ul>
            </div>
          ))}
        </div>
        <div className="footer__bottom">
          <div>© 2026 {window.COPY.brandName}. All rights reserved.</div>
          <div>{f.tagline}</div>
        </div>
      </div>
    </footer>
  );
};

// Newsletter capture modal. Triggered:
//   - Once per browser, on a 30s timer if the user hasn't dismissed
//     (localStorage rs_newsletter_seen=1).
//   - Manually via window.dispatchEvent(new Event("restager:open-newsletter")).
// Captures email + (optional) marketing opt-in. POSTs to /api/subscribe.
// On success, awards +1 bonus credit (server-side) and shows a
// confirmation. Dismissing or submitting both set the localStorage
// flag so we don't badger the user.
const NewsletterModal = () => {
  const [shown, setShown] = React.useState(false);
  const [email, setEmail] = React.useState("");
  const [marketingOptIn, setMarketingOptIn] = React.useState(true);
  const [submitting, setSubmitting] = React.useState(false);
  const [done, setDone] = React.useState(null); // null | { bonusAwarded }
  const [err, setErr] = React.useState(null);
  const [origin, setOrigin] = React.useState("manual");

  // Auto-trigger after 30s + manual trigger via custom event.
  React.useEffect(() => {
    let already = false;
    try { already = localStorage.getItem("rs_newsletter_seen") === "1"; } catch {}
    const open = (src) => {
      if (already) return;
      setOrigin(src);
      setShown(true);
    };
    const t = setTimeout(() => open("auto"), 30000);
    const handler = () => open("manual");
    window.addEventListener("restager:open-newsletter", handler);
    return () => { clearTimeout(t); window.removeEventListener("restager:open-newsletter", handler); };
  }, []);

  const dismiss = () => {
    try { localStorage.setItem("rs_newsletter_seen", "1"); } catch {}
    setShown(false);
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!email || submitting) return;
    setSubmitting(true); setErr(null);
    try {
      const lang = window.APP_LANG || "en";
      const r = await fetch("/api/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "same-origin",
        body: JSON.stringify({ email, marketingOptIn, locale: lang, source: origin === "manual" ? "marketing-banner" : "auto-modal" }),
      });
      const j = await r.json();
      if (!r.ok) { setErr(j.message || "Subscription failed."); return; }
      try { localStorage.setItem("rs_newsletter_seen", "1"); } catch {}
      setDone({ bonusAwarded: !!j.bonusAwarded });
    } catch {
      setErr("Network error. Try again.");
    } finally { setSubmitting(false); }
  };

  if (!shown) return null;

  const lang = window.APP_LANG || "en";
  const T = lang === "lt" ? {
    headline: "Gauk dar 1 nemokamą apstatymą",
    body: "Palik el. paštą - pridėsime bonusinį kreditą prie tavo paskyros. Šlamšto neisiunčiame; rašome retai apie naujus stilius ar pakeitimus.",
    placeholder: "tu@pastas.lt",
    optIn: "Taip, retkarčiais norėčiau gauti naujienas (gali atsisakyti bet kada).",
    cta: "Aktyvuoti bonusinį kreditą",
    submitting: "Siunčiama...",
    dismiss: "Ne dabar",
    successTitle: "Ačiū!",
    successBodyBonus: "Bonusinis kreditas pridėtas. Patvirtinimo laiškas keliauja į pašto dėžutę.",
    successBodyNoBonus: "Užregistruota. Dėkui, kad prisijungei.",
    close: "Uždaryti",
  } : {
    headline: "Get +1 free staging",
    body: "Drop your email and we'll add a bonus credit to your account. No spam - only the occasional update on new styles or app changes.",
    placeholder: "you@email.com",
    optIn: "Yes, send me the occasional update (unsubscribe any time).",
    cta: "Claim my bonus credit",
    submitting: "Sending...",
    dismiss: "Not now",
    successTitle: "Thanks!",
    successBodyBonus: "Your bonus credit is live. Confirmation email is on its way.",
    successBodyNoBonus: "You're on the list. Thanks for joining.",
    close: "Close",
  };

  return (
    <div className="nl-modal" onClick={dismiss}>
      <div className="nl-card" onClick={(e) => e.stopPropagation()}>
        {done ? (
          <>
            <h3>{T.successTitle}</h3>
            <p>{done.bonusAwarded ? T.successBodyBonus : T.successBodyNoBonus}</p>
            <div style={{ textAlign: "right" }}>
              <button className="nl-btn nl-btn-primary" onClick={dismiss}>{T.close}</button>
            </div>
          </>
        ) : (
          <form onSubmit={submit}>
            <h3>{T.headline}</h3>
            <p>{T.body}</p>
            <input
              type="email"
              required
              placeholder={T.placeholder}
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="nl-input"
            />
            <label className="nl-optin">
              <input type="checkbox" checked={marketingOptIn} onChange={(e) => setMarketingOptIn(e.target.checked)}/>
              <span>{T.optIn}</span>
            </label>
            {err && <div className="nl-err">{err}</div>}
            <div className="nl-actions">
              <button type="button" className="nl-btn" onClick={dismiss}>{T.dismiss}</button>
              <button type="submit" className="nl-btn nl-btn-primary" disabled={submitting}>
                {submitting ? T.submitting : T.cta}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
};

// One-time cookie notice. We don't run advertising or third-party analytics
// cookies, only an auth session cookie + Cloudflare Turnstile's bot-check
// cookies. Under EU rules those are "strictly necessary" so consent is not
// required - but a transparent notice is still expected. We dismiss on
// click and remember in localStorage so it shows once per browser.
const CookieBanner = () => {
  const [shown, setShown] = React.useState(false);

  React.useEffect(() => {
    try {
      const ack = localStorage.getItem("rs_cookie_ack");
      if (!ack) setShown(true);
    } catch {
      // localStorage unavailable (private mode etc.) - just don't show.
    }
  }, []);

  const dismiss = () => {
    try { localStorage.setItem("rs_cookie_ack", "1"); } catch {}
    setShown(false);
  };

  if (!shown) return null;

  const lang = window.APP_LANG || "en";
  const T = lang === "lt" ? {
    body: "Naudojame tik būtinus slapukus, kad veiktų prisijungimas ir botų patikra. Jokios reklamos ar trečiųjų šalių sekimo.",
    learn: "Daugiau",
    ok: "Supratau",
    href: "/privacy-lt.html",
  } : {
    body: "We only use essential cookies for sign-in and bot verification. No ads, no third-party tracking.",
    learn: "Learn more",
    ok: "Got it",
    href: "/privacy.html",
  };

  // Inline styles so the banner doesn't depend on styles.css. Z-index high
  // enough to clear the Tweaks panel and the announce banner. backdrop-blur
  // gives it a soft frame on top of any page section.
  const wrap = {
    position: "fixed",
    bottom: 16,
    left: 16,
    right: 16,
    maxWidth: 720,
    margin: "0 auto",
    padding: "14px 18px",
    background: "rgba(18, 19, 21, 0.96)",
    color: "#f4efe1",
    borderRadius: 12,
    boxShadow: "0 8px 32px rgba(0,0,0,0.18)",
    fontFamily: "Inter, system-ui, -apple-system, sans-serif",
    fontSize: 14,
    lineHeight: 1.5,
    display: "flex",
    flexWrap: "wrap",
    alignItems: "center",
    gap: 14,
    zIndex: 100000,
  };
  const linkStyle = { color: "#f4efe1", textDecoration: "underline" };
  const btn = {
    appearance: "none",
    border: "none",
    background: "#f4efe1",
    color: "#121315",
    padding: "8px 14px",
    borderRadius: 8,
    fontWeight: 600,
    fontSize: 13,
    cursor: "pointer",
    marginLeft: "auto",
  };

  return (
    <div role="region" aria-label="Cookie notice" style={wrap}>
      <span>{T.body} <a href={T.href} style={linkStyle}>{T.learn}</a></span>
      <button type="button" onClick={dismiss} style={btn}>{T.ok}</button>
    </div>
  );
};

Object.assign(window, { Hero, Trust, Steps, Gallery, Styles, Features, LogoStrip, Testimonials, Pricing, Faq, CtaBlock, Footer, Heading, CookieBanner });
