/* global React, Icons, ResumePaper, SAMPLE_RESUME, ScaleDots, ScaleSegs, ScaleSignal */
// ============================================================
//  Landing — bright, conversion-style marketing page
// ============================================================
const { useState, useEffect, useRef } = React;

// count-up animation (runs once when mounted / scrolled into view)
function CountUp({ to, dur = 1500, suffix = "" }) {
  const [n, setN] = useState(0);
  const ref = useRef(null);
  const done = useRef(false);
  useEffect(() => {
    const run = () => {
      if (done.current) return;done.current = true;
      let start;
      const ease = (x) => 1 - Math.pow(1 - x, 3);
      const tick = (t) => {
        if (!start) start = t;
        const p = Math.min(1, (t - start) / dur);
        setN(Math.round(ease(p) * to));
        if (p < 1) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    };
    const node = ref.current;
    let io;
    if (node && "IntersectionObserver" in window) {
      io = new IntersectionObserver((es) => {es.forEach((e) => e.isIntersecting && run());}, { threshold: 0.3 });
      io.observe(node);
    }
    // fallback so counters always animate even if the observer never fires
    const t = setTimeout(run, 900);
    // safety snap: guarantee the final value shows even if rAF is throttled
    const snap = setTimeout(() => setN(to), 2600);
    return () => {if (io) io.disconnect();clearTimeout(t);clearTimeout(snap);};
  }, [to, dur]);
  return <span ref={ref} style={{ fontSize: "25px", color: "rgb(166, 202, 81)" }}>{n.toLocaleString()}{suffix}</span>;
}

// little gradient score ring for the hero float card
function MiniScore({ score = 92, size = 40 }) {
  const R = 16,C = 2 * Math.PI * R;
  return (
    <span className="mini-score">
      <svg width={size} height={size} viewBox="0 0 40 40">
        <circle cx="20" cy="20" r={R} fill="none" stroke="var(--bg-4)" strokeWidth="4" />
        <circle cx="20" cy="20" r={R} fill="none" stroke="url(#mg)" strokeWidth="4" strokeLinecap="round"
        strokeDasharray={C} strokeDashoffset={C * (1 - score / 100)} transform="rotate(-90 20 20)" />
        <defs><linearGradient id="mg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="var(--acc)" /><stop offset="1" stopColor="var(--acc-2)" /></linearGradient></defs>
      </svg>
      <b>{score}</b>
    </span>);

}

const STARS = (n = 5) => [...Array(n)].map((_, i) => <Icons.star key={i} size={14} fill />);

// testimonial avatar — self-contained striped photo placeholder (tinted per person)
function Avatar({ name, c }) {
  return (
    <span className="testi-av testi-av-ph" style={{ "--av": c }} title={`${name} — photo`} aria-label={`${name} photo placeholder`}>
      <Icons.user size={17} />
    </span>);

}

// typewriter that types each phrase, holds, deletes, advances — used in the AI demo
function Typewriter({ phrases, speed = 34, hold = 1700 }) {
  const [txt, setTxt] = useState("");
  const [idx, setIdx] = useState(0);
  const [del, setDel] = useState(false);
  useEffect(() => {
    const cur = phrases[idx % phrases.length];
    let t;
    if (!del && txt === cur) t = setTimeout(() => setDel(true), hold);else
    if (del && txt === "") {setDel(false);setIdx((i) => i + 1);} else
    t = setTimeout(() => setTxt(del ? cur.slice(0, txt.length - 1) : cur.slice(0, txt.length + 1)), del ? 18 : speed);
    return () => clearTimeout(t);
  }, [txt, del, idx, phrases, speed, hold]);
  return <span className="tw">{txt}<i className="tw-caret" /></span>;
}

// "hired at" logo wall — real monochrome brand marks via Simple Icons CDN,
// with a graceful fallback to the wordmark if a logo isn't available.
const LOGOS = [
{ slug: "google", name: "Google" },
{ slug: "airbnb", name: "Airbnb" },
{ slug: "spotify", name: "Spotify" },
{ slug: "stripe", name: "Stripe" },
{ slug: "figma", name: "Figma" },
{ slug: "notion", name: "Notion" },
{ slug: "dropbox", name: "Dropbox" },
{ slug: "github", name: "GitHub" },
{ slug: "slack", name: "Slack" },
{ slug: "uber", name: "Uber" },
{ slug: "netflix", name: "Netflix" },
{ slug: "amazon", name: "Amazon" },
{ slug: "adobe", name: "Adobe" },
{ slug: "salesforce", name: "Salesforce" },
{ slug: "atlassian", name: "Atlassian" },
{ slug: "shopify", name: "Shopify" },
{ slug: "coinbase", name: "Coinbase" },
{ slug: "linkedin", name: "LinkedIn" }];

function BrandLogo({ slug, name }) {
  const [err, setErr] = useState(false);
  if (err) return <span className="m-logo">{name}</span>;
  return (
    <img className="m-logo-img" src={`https://cdn.simpleicons.org/${slug}/14140a`}
    alt={name} title={name} loading="lazy" onError={() => setErr(true)} />);

}

function Landing({ onStart, onGallery, onCovers, onPrivacy, onRefund, onContact }) {
  const [demoTpl, setDemoTpl] = useState("meridian");
  const tpls = window.TEMPLATES;

  useEffect(() => {
    const order = ["meridian", "spectrum", "helix", "ember", "veritas", "onyx", "marigold", "quill"];
    let i = 0;
    const id = setInterval(() => {i = (i + 1) % order.length;setDemoTpl(order[i]);}, 3000);
    return () => clearInterval(id);
  }, []);

  // reveal section headers with motion as they scroll into view (scroll-based —
  // robust across embedded/scaled contexts where IntersectionObserver misbehaves)
  useEffect(() => {
    const els = [...document.querySelectorAll(".landing .sec-head, .landing .eyebrow")];
    els.forEach((el) => el.classList.add("reveal-init"));
    let ticking = false;
    const check = () => {
      ticking = false;
      const vh = window.innerHeight || document.documentElement.clientHeight;
      els.forEach((el) => {
        if (!el.classList.contains("reveal-init")) return;
        const r = el.getBoundingClientRect();
        if (r.top < vh * 0.9 && r.bottom > 0) {el.classList.add("reveal-in");el.classList.remove("reveal-init");}
      });
    };
    const onScroll = () => {if (!ticking) {ticking = true;requestAnimationFrame(check);}};
    check();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    // safety: reveal everything shortly after load even if no scroll happens
    const t = setTimeout(() => els.forEach((el) => {el.classList.add("reveal-in");el.classList.remove("reveal-init");}), 2500);
    return () => {window.removeEventListener("scroll", onScroll);window.removeEventListener("resize", onScroll);clearTimeout(t);};
  }, []);

  return (
    <div className="landing">
      {/* ===== hero ===== */}
      <section className="hero wrap">
        <div className="hero-copy">
          <div className="chip rise" style={{ animationDelay: "0.05s" }}>
            <Icons.spark size={14} style={{ color: "var(--acc)" }} /> Free AI résumé builder
          </div>
          <h1 className="hero-title rise" style={{ animationDelay: "0.12s" }}>
            Build a résumé that<br />
            <span className="grad">gets you hired.</span>
          </h1>
          <p className="hero-sub rise" style={{ animationDelay: "0.2s" }}>
            Pick a design, add your details, and let AI write every line for you.
            Your résumé is ready in <b>minutes</b> — free to start, and built to
            get past screening bots and impress real recruiters.
          </p>
          <div className="hero-cta rise" style={{ animationDelay: "0.28s" }}>
            <button className="btn btn-primary btn-lg" onClick={onStart}>
              Create my résumé — free <Icons.arrow size={17} />
            </button>
            <button className="btn btn-ghost btn-lg" onClick={onGallery}>
              <Icons.grid size={16} /> See the designs
            </button>
          </div>
          <p className="hero-free rise" style={{ animationDelay: "0.32s", display: "flex", alignItems: "center", gap: "8px", margin: "16px 0 0", fontSize: "13.5px", color: "var(--ink-3)" }}>
            <Icons.check size={14} style={{ color: "var(--acc)", flex: "none" }} />
            Free to build, edit &amp; copy as text — no sign-up. PDF downloads with Pro.
          </p>
          <div className="trust rise" style={{ animationDelay: "0.36s" }}>
            <span className="trust-pill"><b>Excellent</b><span className="trust-stars">{STARS(5)}</span></span>
            <span className="trust-txt"><b>4.8</b> / 5 · <CountUp to={12480} /> reviews</span>
          </div>
        </div>

        <div className="hero-stage rise" style={{ animationDelay: "0.3s" }}>
          <div className="stage-glow" />
          <div className="stage-paper" key={demoTpl}>
            <ResumePaper data={SAMPLE_RESUME} templateId={demoTpl} />
          </div>
          <div className="stage-dots">
            {["meridian", "spectrum", "helix", "ember", "veritas", "onyx", "marigold", "quill"].map((id) =>
            <button key={id} className={`s-dot ${demoTpl === id ? "on" : ""}`}
            onClick={() => setDemoTpl(id)} aria-label={id} />
            )}
          </div>
          <div className="float-card fc-score glass">
            <MiniScore score={92} />
            <div><b>Résumé score 92</b><span>Strong · recruiter-ready</span></div>
          </div>
          <div className="float-card fc-ats glass">
            <div className="ring"><Icons.check size={14} /></div>
            <div><b>ATS-perfect</b><span>Parsed by every tracker</span></div>
          </div>
          <div className="float-card fc-skill glass" style={{ "--pa": "var(--acc)" }}>
            <div className="fc-skill-h">Skills</div>
            <div className="fc-skill-row"><span>Figma</span><ScaleDots level={5} /></div>
            <div className="fc-skill-row"><span>React</span><ScaleDots level={4} /></div>
            <div className="fc-skill-row"><span>Motion</span><ScaleDots level={4} /></div>
          </div>
        </div>
      </section>

      {/* ===== logos ===== */}
      <section className="marquee-wrap fade" style={{ animationDelay: "0.5s" }}>
        <span className="marquee-label">People here got hired at</span>
        <div className="marquee-view">
          <div className="marquee">
            {[0, 1].map((g) =>
            <div className="m-track" key={g} aria-hidden={g === 1}>
                {LOGOS.map((l, i) => <BrandLogo key={i} slug={l.slug} name={l.name} />)}
              </div>
            )}
          </div>
        </div>
      </section>

      {/* ===== build-mode chooser ===== */}
      <section className="wrap chooser">
        <div className="eyebrow">Get started</div>
        <h2 className="sec-head">Two easy ways to begin.</h2>
        <div className="chooser-panel">
          <div className="chooser-grid">
            <button className="choose-card" onClick={onGallery}>
              <span className="choose-ic new"><Icons.plus size={26} /></span>
              <h3>Start from scratch</h3>
              <p>We guide you step by step and suggest what to write — no experience needed.</p>
              <span className="choose-go">Start building <Icons.arrow size={15} /></span>
            </button>
            <button className="choose-card" onClick={onStart}>
              <span className="choose-ic up"><Icons.download size={24} /></span>
              <h3>Already have one?</h3>
              <p>Bring your old résumé and we'll turn it into a sharp, modern design.</p>
              <span className="choose-go">Refresh mine <Icons.arrow size={15} /></span>
            </button>
          </div>
        </div>
      </section>

      {/* ===== AI layer highlight ===== */}
      <section className="wrap split ai-hl">
        <div className="split-copy">
          <div className="eyebrow">Writes it for you</div>
          <h2 className="sec-head">Not sure what to write? <em>AI does it.</em></h2>
          <p className="split-p">
            Just type what you did in plain words. AI turns it into polished,
            impressive lines that sound like a pro wrote them — matched to the
            job you want. No more staring at a blank page.
          </p>
          <ul className="check-list">
            <li><Icons.check size={15} /> Fix, shorten, or punch up any line in one click</li>
            <li><Icons.check size={15} /> Writes your summary and bullet points from scratch</li>
            <li><Icons.check size={15} /> Tuned to the exact job you're applying for</li>
          </ul>
          <button className="btn btn-primary" onClick={onStart}>Write with AI <Icons.arrow size={16} /></button>
        </div>
        <div className="split-visual">
          <div className="ai-mock">
            <div className="ai-mock-h"><span className="ai-mock-ic"><Icons.magic size={15} /></span> AI rewrite <span className="ai-mock-live">live</span></div>
            <div className="ai-line ai-before">
              <span className="ai-tagline">Your note</span>
              <p>“managed social media and grew the following”</p>
            </div>
            <div className="ai-arrow"><span><Icons.magic size={13} /> Rewrite with impact</span></div>
            <div className="ai-line ai-after">
              <span className="ai-tagline">AI suggestion</span>
              <p><Typewriter phrases={[
                "Grew Instagram audience 3× to 48K, lifting referral traffic 22%.",
                "Launched a content engine that drove 1.2M impressions in six months.",
                "Boosted engagement 41% with a data-driven posting cadence."]
                } /></p>
            </div>
            <div className="ai-prompt">
              <Icons.spark size={14} />
              <span>Ask AI to make it stronger…</span>
              <button className="ai-send"><Icons.arrow size={14} /></button>
            </div>
          </div>
        </div>
      </section>

      {/* ===== proficiency scale highlight (new feature) ===== */}
      <section className="wrap split scale-hl">
        <div className="split-copy">
          <div className="eyebrow">Stand out</div>
          <h2 className="sec-head">Show how good you are — not just <em>what</em> you know.</h2>
          <p className="split-p">
            Rate your skills on a simple 1-to-5 scale. Recruiters instantly see
            where you shine, and your résumé looks like an expert made it. Pick the
            style you like: subtle dots, bold bars, or equalizer signals.
          </p>
          <ul className="check-list">
            <li><Icons.check size={15} /> Per-skill levels, edited with a tap</li>
            <li><Icons.check size={15} /> Auto-styled to match your template</li>
            <li><Icons.check size={15} /> Languages rated the same way</li>
          </ul>
          <button className="btn btn-primary" onClick={onGallery}>Show me how <Icons.arrow size={16} /></button>
        </div>
        <div className="split-visual">
          <div className="scale-card" style={{ "--pa": "var(--acc)" }}>
            <div className="sc-h"><Icons.star size={15} /> Skills</div>
            {[["Figma", 5], ["Prototyping", 5], ["React", 4], ["TypeScript", 3]].map(([n, l]) =>
            <div className="sc-row" key={n}><span>{n}</span><ScaleDots level={l} /></div>
            )}
            <div className="sc-styles">
              <div><span>Dots</span><ScaleDots level={4} /></div>
              <div><span>Segments</span><ScaleSegs level={4} /></div>
              <div><span>Signal</span><ScaleSignal level={4} /></div>
            </div>
          </div>
        </div>
      </section>

      {/* ===== feature trio ===== */}
      <section className="wrap features">
        {[
        { ic: Icons.magic, t: "AI writes it for you", d: "Type what you did in plain words. AI turns it into polished, impressive lines in one click.", ai: true, c: "#7deb00" },
        { ic: Icons.layers, t: "50+ designs you'll love", d: "Beautiful layouts for every field — modern, classic, minimal. Switch anytime without losing a word.", c: "#4f9dff" },
        { ic: Icons.bolt, t: "A score that guides you", d: "A live score shows exactly what to add or fix — so you send something that gets noticed.", c: "#ffb43d" }].
        map((f, i) =>
        <div className="feat-card" key={i} style={{ "--c": f.c, animationDelay: `${0.1 + i * 0.08}s` }}>
            {f.ai && <span className="ai-tag"><Icons.spark size={12} /> AI-powered</span>}
            <div className="feat-ic"><f.ic size={20} /></div>
            <h3>{f.t}</h3>
            <p>{f.d}</p>
          </div>
        )}
      </section>

      {/* ===== bento grid ===== */}
      <section className="wrap bento-sec">
        <div className="eyebrow">Everything in one studio</div>
        <h2 className="sec-head">More ways to land the role.</h2>
        <div className="bento">
          <article className="b-card b-a" style={{ "--c": "#7deb00" }}>
            <span className="b-ic"><Icons.magic size={22} /></span>
            <h3>AI that writes for you</h3>
            <p>Turn rough notes into crisp, quantified bullets. Rewrite, shorten, or punch up any line — in your voice.</p>
            <div className="b-chips">
              <span><Icons.spark size={12} /> Rewrite</span>
              <span><Icons.bolt size={12} /> Quantify</span>
              <span><Icons.check size={12} /> Shorten</span>
            </div>
          </article>

          <article className="b-card b-fill" style={{ "--c": "#2fd07f" }}>
            <span className="b-ic"><Icons.check size={20} /></span>
            <h3>Beats the robots</h3>
            <p>Reads cleanly in every hiring system.</p>
          </article>

          <article className="b-card b-score" style={{ "--c": "#ffb43d" }}>
            <span className="b-big">92</span>
            <h3>Live strength score</h3>
            <p>Know exactly what to fix.</p>
          </article>

          <article className="b-card b-d b-templates b-fill" style={{ "--c": "#4f9dff" }}>
            <span className="b-num">50</span>
            <div className="b-templates-txt">
              <h3>designs for every field</h3>
              <p>Modern, classic, minimal, bold — switch anytime without losing a word.</p>
            </div>
          </article>

          <article className="b-card" style={{ "--c": "#ff5ca8" }}>
            <span className="b-ic"><Icons.star size={20} /></span>
            <h3>Skill scales</h3>
            <div className="b-scale" style={{ "--pa": "#ff5ca8" }}><ScaleDots level={5} /><ScaleDots level={4} /></div>
          </article>

          <article className="b-card b-clickable" style={{ "--c": "#2dd4bf" }} onClick={onCovers} role="button" tabIndex={0}>
            <span className="b-ic"><Icons.pen size={20} /></span>
            <h3>Cover letters</h3>
            <p>Matched to your field, in a click.</p>
            <span className="choose-go" style={{ marginTop: "auto" }}>Browse templates <Icons.arrow size={14} /></span>
          </article>

          <article className="b-card b-fill" style={{ "--c": "#ff8a4c" }}>
            <span className="b-ic"><Icons.download size={20} /></span>
            <h3>One-click PDF</h3>
            <p>Pixel-perfect, print-ready.</p>
          </article>

          <article className="b-card" style={{ "--c": "#38d6e6" }}>
            <span className="b-ic"><Icons.eye size={20} /></span>
            <h3>See who's looking</h3>
            <p>Know when an employer opens it.</p>
          </article>

          <article className="b-card b-d b-tailor" style={{ "--c": "#a3e635" }}>
            <span className="b-ic"><Icons.bolt size={20} /></span>
            <div className="b-tailor-txt">
              <h3>Made for the job you want</h3>
              <p>Paste the job post — we match the keywords and tune every line so you fit the role.</p>
            </div>
            <div className="b-chips">
              <span><Icons.spark size={12} /> Keyword match</span>
              <span><Icons.check size={12} /> Role-tuned</span>
            </div>
          </article>

          <article className="b-card b-score" style={{ "--c": "#c08bff" }}>
            <span className="b-big">4.8<span className="b-big-d">★</span></span>
            <h3>Maker rating</h3>
            <p>12,480 reviews.</p>
          </article>

          <article className="b-card" style={{ "--c": "#5ad1ff" }}>
            <span className="b-ic"><Icons.eye size={20} /></span>
            <h3>Live preview</h3>
            <p>Every edit, instantly.</p>
          </article>
        </div>
      </section>

      {/* ===== step-by-step showcase ===== */}
      <section className="wrap split steps-hl">
        <div className="split-visual">
          <div className="guide-card">
            <div className="guide-h"><b>Your résumé</b><span className="guide-prog">3 of 5 done</span></div>
            {[
            ["Personal details", true], ["Professional summary", true],
            ["Skills & levels", "active"], ["Experience", false], ["Education", false]].
            map(([t, st], i) =>
            <div className={`guide-step ${st === true ? "done" : st === "active" ? "active" : ""}`} key={t}>
                <span className="guide-n">{st === true ? <Icons.check size={13} /> : i + 1}</span>
                <span className="guide-t">{t}</span>
                {st === "active" && <Icons.pen size={13} />}
              </div>
            )}
          </div>
        </div>
        <div className="split-copy">
          <div className="eyebrow">How it works</div>
          <h2 className="sec-head">Guided, section by section.</h2>
          <p className="split-p">
            No blank-page stress. We walk you through each part, show you exactly
            what to add, and check it off as you go. Stuck on wording? AI suggests
            lines that sound professional.
          </p>
          <div className="mini-steps">
            <div><span className="ms-n">01</span><h4>Choose a template</h4><p>Pick a layout that fits your field.</p></div>
            <div><span className="ms-n">02</span><h4>Add your story</h4><p>Fill sections or paste an old résumé.</p></div>
            <div><span className="ms-n">03</span><h4>Polish &amp; export</h4><p>Sharpen with AI, download a clean PDF.</p></div>
          </div>
        </div>
      </section>

      {/* ===== testimonials ===== */}
      <section className="wrap testi">
        <div className="eyebrow">Loved by job seekers</div>
        <h2 className="sec-head">People get hired with this.</h2>
        <div className="testi-grid">
          {[
          { q: "Switched careers in six weeks. The strength score told me exactly what was missing before I hit send.", n: "Priya Nair", r: "Product Designer", c: "#6a4dff", img: 47 },
          { q: "The skill scales made my résumé look senior. Three callbacks in the first week.", n: "Marcus Lee", r: "Frontend Engineer", c: "#0e9f8e", img: 12 },
          { q: "Pasted my old PDF, picked a template, done. It finally looks like I take myself seriously.", n: "Sofía Ramírez", r: "Marketing Lead", c: "#e23d7a", img: 45 }].
          map((t, i) =>
          <div className="testi-card" key={i}>
              <div className="testi-stars">{STARS(5)}</div>
              <p className="testi-q">“{t.q}”</p>
              <div className="testi-who">
                <Avatar name={t.n} c={t.c} img={t.img} />
                <div><b>{t.n}</b><span>{t.r}</span></div>
              </div>
            </div>
          )}
        </div>
      </section>

      {/* ===== CTA ===== */}
      <section className="wrap cta-band">
        <div className="cta-inner">
          <div className="cta-aura" />
          <h2>Your next role starts<br />with a better résumé.</h2>
          <p className="cta-sub">Free to build. Beautiful by default. Ready in minutes.</p>
          <button className="btn btn-primary btn-lg" onClick={onStart}>
            Build mine free <Icons.arrow size={17} />
          </button>
        </div>
      </section>

      <footer className="foot wrap">
        <div className="foot-brand">
          <div className="brand"><span className="brand-mark"><Icons.pen size={16} /></span> get-resume</div>
          <p>AI résumés &amp; cover letters for the modern job seeker. A {"Nestaa"} product.</p>
        </div>
        <div className="foot-cols">
          <div className="foot-col"><b>Product</b><a onClick={onGallery}>Templates</a><a onClick={onStart}>Builder</a><a onClick={onStart}>AI writing</a></div>
          <div className="foot-col"><b>Resources</b><a onClick={onGallery}>Résumé designs</a><a onClick={onCovers}>Cover letters</a><a onClick={onContact}>Contact us</a></div>
          <div className="foot-col"><b>Legal</b><a onClick={onPrivacy}>Privacy Policy</a><a onClick={onRefund}>Refund &amp; Cancellation</a><a onClick={onContact}>Contact</a></div>
        </div>
      </footer>
    </div>);

}

window.Landing = Landing;