/* global React */
const { useState: useStateB, useEffect: useEffectB, useRef: useRefB } = React;
const { Icon: IconB, Sparkle: SparkleB, Button: ButtonB } = window;

// ── AI Companion ────────────────────────────────────────────────────
const CAPS = [
  { icon: "pulse", title: "Life Pulse",
    desc: "Real-time HRV, sleep, activity load. When you're running on empty, LIFE notices before your next meeting does." },
  { icon: "energy", title: "Energy Model",
    desc: "Learns when you're sharp, when you crash, when you need a buffer. Defends your peak hours automatically." },
  { icon: "link", title: "Insight Linker",
    desc: "Connects finance, health, goals and calendar to surface patterns none of them could reveal alone." },
  { icon: "chat", title: "Meeting Prep",
    desc: "Auto-briefing before every call: who, what was last discussed, open action items, what to walk out with." },
  { icon: "camera", title: "Camera AI",
    desc: "Photograph a receipt, whiteboard, business card, menu. LIFE extracts, categorises, files. No typing." },
];

const DIALOGUE = [
  { who: "user", text: "Reviewing your week…" },
  { who: "life", text: "You have 4 deliverables due Friday and your Thursday is back-to-back. Based on your energy patterns, Wednesday morning is your sharpest focus window. Want me to move the gym there and protect Thursday 7–9 PM for deep work?" },
  { who: "user", text: "Yes — do it. And find a time Saturday for brunch with Farah." },
  { who: "life", text: "Done. Gym moved, Thursday 7–9 PM protected. Farah's free from 10 AM Saturday. Shall I suggest that cafe in Tiong Bahru — you both rated it highly last visit — and send her the invite?" },
  { who: "user", text: "Yes. Send it." },
];

const Typewriter = ({ text, speed = 18, onDone }) => {
  const [out, setOut] = useStateB("");
  useEffectB(() => {
    let i = 0;
    setOut("");
    const id = setInterval(() => {
      i++;
      setOut(text.slice(0, i));
      if (i >= text.length) {
        clearInterval(id);
        onDone && onDone();
      }
    }, speed);
    return () => clearInterval(id);
  }, [text]);
  return <>{out}</>;
};

const DialogueStream = () => {
  const [n, setN] = useStateB(0);  // index of message currently typing
  const [done, setDone] = useStateB(0); // count of fully-completed
  const [thinking, setThinking] = useStateB(false);
  const streamRef = useRefB(null);

  useEffectB(() => {
    if (n >= DIALOGUE.length) {
      // hold then loop
      const t = setTimeout(() => { setN(0); setDone(0); }, 4500);
      return () => clearTimeout(t);
    }
    // before "life" replies, show thinking pulse
    if (DIALOGUE[n].who === "life" && !thinking) {
      setThinking(true);
      const t = setTimeout(() => setThinking(false), 900);
      return () => clearTimeout(t);
    }
  }, [n, thinking]);

  useEffectB(() => {
    if (streamRef.current) streamRef.current.scrollTop = streamRef.current.scrollHeight;
  });

  return (
    <div className="dialogue-card" data-reveal>
      <div className="dialogue-inner">
        <div className="dialogue-header">
          <div className="dialogue-title">
            <span className="live-dot"></span>
            <span>LIFE — Tuesday 7:14 AM</span>
          </div>
          <div className="preview-time">Live</div>
        </div>
        <div className="dialogue-stream" ref={streamRef}>
          {DIALOGUE.slice(0, done).map((m, i) => (
            <div key={i} className={`msg msg-${m.who}`}>
              <div className="msg-bubble">
                {m.who === "life" && (
                  <div className="ai-glyph">
                    <span className="ai-icon-glow"><IconB name="aiLeaf" size={14} color="#33FFE9" /></span>
                    LIFE
                  </div>
                )}
                {m.text}
              </div>
            </div>
          ))}
          {n < DIALOGUE.length && DIALOGUE[n].who === "life" && thinking && (
            <div className="msg msg-life">
              <div className="typing-dots"><span></span><span></span><span></span></div>
            </div>
          )}
          {n < DIALOGUE.length && !thinking && (
            <div className={`msg msg-${DIALOGUE[n].who}`}>
              <div className="msg-bubble">
                {DIALOGUE[n].who === "life" && (
                  <div className="ai-glyph">
                    <span className="ai-icon-glow"><IconB name="aiLeaf" size={14} color="#33FFE9" /></span>
                    LIFE
                  </div>
                )}
                <Typewriter
                  text={DIALOGUE[n].text}
                  speed={DIALOGUE[n].who === "user" ? 28 : 16}
                  onDone={() => { setDone(d => d + 1); setN(v => v + 1); }}
                />
              </div>
            </div>
          )}
        </div>
        <div className="preview-meta" style={{ marginTop: 14 }}>
          <span className="preview-meta-tag">
            <SparkleB size={11} /> Quietly handled
          </span>
          <span>Calendar · Health · Social</span>
        </div>
      </div>
    </div>
  );
};

const AICompanion = () => (
  <section className="section ai-section" id="ai">
    <div className="container">
      <div className="ai-grid">
        <div>
          <div className="kicker" data-reveal><span className="kicker-dot"></span>Your AI companion</div>
          <h2 className="h-section" data-reveal style={{ marginTop: 16 }}>
            The only assistant that knows your whole life.
          </h2>
          <p className="lead" data-reveal style={{ marginTop: 22, color: "#2D3436" }}>
            Most AI tools answer questions. LIFE's AI acts. It reads your wearables, your calendar,
            your goals, your social circle and your finances — all at once. It doesn't wait to be asked.
            It spots the problems before you ever feel them.
          </p>
          <div className="ai-cap-list">
            {CAPS.map((c) => (
              <div className="ai-cap" key={c.title} data-reveal>
                <span className="ai-cap-icon"><IconB name={c.icon} size={20} color="#33FFE9" /></span>
                <div>
                  <h4>{c.title}</h4>
                  <p>{c.desc}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
        <DialogueStream />
      </div>
    </div>
  </section>
);

// ── Results / Stories ───────────────────────────────────────────────
const STORIES = [
  {
    name: "Reza", role: "Founder, late 30s · Singapore",
    circle: "#1B4332", sprig: "#A7D7C5",
    situation: "Six-figure spend, three months of revenue volatility.",
    quote: <>Found <span className="num">$3,400</span> a month in costs that didn't earn their keep — and the discipline to redirect it.</>,
    outcome: "Subscriptions and Finance flagged drift Reza's accountant hadn't caught. Goals translated the saving into a runway target. Three quarters in, his cash position is steadier than it's been in two years.",
    pills: [{ label: "Finance", color: "#F2C94C" }, { label: "Subscriptions", color: "#F2C94C" }, { label: "Goals", color: "#F2A07B" }],
  },
  {
    name: "Selin", role: "Strategy lead · Istanbul",
    circle: "#5B8A72", sprig: "#CDEB45",
    situation: "Back-to-back days, no time to think, sliding sleep.",
    quote: <>Got <span className="num">6.5</span> hours of deep work back, every week — without working later.</>,
    outcome: "Energy Model learned her real peak (9–11 AM) and made it sacred. Calendar moved standing meetings out. Health caught a recovery dip before it became a cold. The late nights stopped.",
    pills: [{ label: "Calendar", color: "#1B4332" }, { label: "Health", color: "#A7D7C5" }, { label: "Tasks", color: "#5B8A72" }],
  },
  {
    name: "Mia", role: "Independent creator · Lisbon",
    circle: "#C3B1E1", sprig: "#FFD96B",
    situation: "Two products, one inbox, weekends going to admin.",
    quote: <>Shipped <span className="num">11</span> pieces last month — the most consistent stretch I've ever had.</>,
    outcome: "Content batched what she used to scatter. Finance kept the freelance numbers honest. Outings put weekends back on the calendar that admin had been quietly stealing.",
    pills: [{ label: "Content", color: "#89C2D9" }, { label: "Finance", color: "#F2C94C" }, { label: "Outings", color: "#89C2D9" }],
  },
  {
    name: "Amir", role: "Senior engineer & dad of two · Berlin",
    circle: "#F2C94C", sprig: "#5B8A72",
    situation: "Four standalone apps, none of them talking to each other.",
    quote: <>One app instead of twelve. <span className="num">~5</span> hours a week back, and the family dinners are protected.</>,
    outcome: "Travel, Calendar and Social moved in together. The kids' schedules merged with work. Periodic Reviews surfaced patterns he'd been blind to. Sundays are Sundays again.",
    pills: [{ label: "Calendar", color: "#1B4332" }, { label: "Travel", color: "#89C2D9" }, { label: "Social", color: "#C3B1E1" }, { label: "Reviews", color: "#F2A07B" }],
  },
];

const Portrait = ({ circle, sprig }) => {
  // Flat-vector illustrated portrait — abstract figure inside a coloured circle, with a botanical sprig and one sparkle.
  return (
    <svg viewBox="0 0 120 120" width="120" height="120" aria-hidden="true">
      <defs>
        <clipPath id={`pc-${circle.replace('#','')}`}>
          <circle cx="60" cy="60" r="58" />
        </clipPath>
      </defs>
      <circle cx="60" cy="60" r="58" fill={circle} />
      <g clipPath={`url(#pc-${circle.replace('#','')})`}>
        {/* warm flat figure: shoulders + head */}
        <ellipse cx="60" cy="118" rx="44" ry="32" fill="rgba(255,255,255,0.18)" />
        <ellipse cx="60" cy="120" rx="32" ry="22" fill="rgba(250,247,242,0.85)" />
        <circle cx="60" cy="78" r="22" fill="#E5C9A8" />
        <path d="M40 70c2-14 12-22 22-22s18 8 18 18c0 4-2 6-2 6-3-6-9-9-16-9s-13 3-16 7l-6 0z" fill="#3a2e22" opacity="0.85" />
        <circle cx="53" cy="80" r="1.5" fill="#3a2e22" />
        <circle cx="68" cy="80" r="1.5" fill="#3a2e22" />
        <path d="M55 87c2 2 6 2 8 0" stroke="#3a2e22" strokeWidth="1.4" strokeLinecap="round" fill="none" />
      </g>
      {/* botanical sprig */}
      <g transform="translate(86 22) rotate(20)">
        <path d="M0 18 C 2 8, 8 2, 16 0" stroke={sprig} strokeWidth="2" fill="none" strokeLinecap="round" />
        <ellipse cx="6" cy="10" rx="3.5" ry="1.6" fill={sprig} transform="rotate(-30 6 10)" />
        <ellipse cx="11" cy="5" rx="3" ry="1.4" fill={sprig} transform="rotate(-10 11 5)" />
      </g>
      {/* sun-gold sparkle */}
      <g transform="translate(98 96)">
        <path d="M0 -7 L1 -1 L7 0 L1 1 L0 7 L-1 1 L-7 0 L-1 -1 Z" fill="#F2C94C" />
      </g>
    </svg>
  );
};

const StoryCard = ({ s }) => (
  <div className="story" data-reveal>
    <div className="story-inner">
      <div className="portrait" style={{ background: "transparent" }}>
        <Portrait circle={s.circle} sprig={s.sprig} />
      </div>
      <div>
        <div className="story-name">{s.name}</div>
        <div className="story-role">{s.role}</div>
        <div className="story-situation">{s.situation}</div>
        <blockquote className="story-quote">"{s.quote}"</blockquote>
        <p className="story-outcome">{s.outcome}</p>
        <div className="module-tags">
          {s.pills.map((p, i) => (
            <span key={i} className="module-tag"
                  style={{ background: `${p.color}26`, color: p.color === "#F2C94C" ? "#8a6f1d" : p.color }}>
              {p.label}
            </span>
          ))}
        </div>
      </div>
    </div>
  </div>
);

const Results = () => (
  <section className="section" id="results" style={{ background: "#FAF7F2" }}>
    <div className="container">
      <div className="kicker" data-reveal><span className="kicker-dot"></span>Real results</div>
      <h2 className="h-section" data-reveal style={{ marginTop: 16, maxWidth: "22ch" }}>
        LIFE isn't for everyone. It's built for people like these.
      </h2>
      <p className="lead" data-reveal style={{ marginTop: 22, color: "#2D3436", maxWidth: "60ch" }}>
        Four early users. Different lives. The same quiet shift — from running on the back foot to
        living a little ahead of yourself.
      </p>
      <div className="results-grid">
        {STORIES.map((s) => <StoryCard key={s.name} s={s} />)}
      </div>
    </div>
  </section>
);

// ── Privacy ─────────────────────────────────────────────────────────
const PRIVACY = [
  { icon: "lock", title: "End-to-end encrypted",
    body: "Everything you store is encrypted in transit and at rest. We can't read your data. Neither can anyone else." },
  { icon: "shield", title: "Zero data selling",
    body: "We make money from subscriptions. Never from your data. Your life is not a product we sell to advertisers." },
  { icon: "hand", title: "You're in control",
    body: "Export your data any time. Delete your account in one tap. No dark patterns. No hostage-taking." },
  { icon: "tree", title: "Built to last",
    body: "LIFE is designed to be a permanent part of your life — not a venture-funded experiment that disappears in two years." },
];

const Privacy = () => (
  <section className="section" id="privacy" style={{ background: "#EAF1E9" }}>
    <div className="container">
      <div className="kicker" data-reveal><span className="kicker-dot"></span>Privacy</div>
      <h2 className="h-section" data-reveal style={{ marginTop: 16 }}>Your data is yours. Full stop.</h2>
      <div className="privacy-grid">
        {PRIVACY.map((p) => (
          <div className="privacy-card" key={p.title} data-reveal>
            <div className="privacy-inner">
              <div className="privacy-icon"><IconB name={p.icon} size={20} /></div>
              <h3>{p.title}</h3>
              <p>{p.body}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// ── Final CTA ───────────────────────────────────────────────────────
const FinalCTA = () => (
  <section className="section final" id="cta">
    <div className="final-blobs hero-blobs">
      <div className="blob blob-a"></div>
      <div className="blob blob-b"></div>
    </div>
    <div className="container">
      <div className="final-inner">
        <div className="kicker" data-reveal><span className="kicker-dot"></span>Early access</div>
        <h2 className="final-wordmark" data-reveal>
          LIVE&nbsp;MORE<br />DELIBERATELY.
        </h2>
        <p className="final-lead" data-reveal>
          The people who get the most from life don't have more time. They have a better system.
          LIFE is in early access — join the waitlist and be among the first to feel what a calm,
          intelligent home for your life looks like.
        </p>
        <div className="cta-row" style={{ justifyContent: "center" }} data-reveal>
          <ButtonB variant="sage" icon="arrow" href="#cta">Claim your early access</ButtonB>
        </div>
        <div className="final-meta" data-reveal>No credit card · No commitment</div>
      </div>
    </div>
  </section>
);

// ── Footer ──────────────────────────────────────────────────────────
const Footer = () => (
  <footer className="foot">
    <div className="container">
      <div className="foot-grid">
        <div>
          <img src="assets/logo-horizontal-light.png" alt="LIFE" style={{ height: 26 }} />
          <p className="foot-blurb">A calm, intelligent home for the things that matter — calendar, money, health, goals, people.</p>
        </div>
        <div className="foot-col">
          <h5>Product</h5>
          <ul>
            <li><a href="#system">17 areas</a></li>
            <li><a href="#ai">AI companion</a></li>
            <li><a href="#privacy">Privacy</a></li>
            <li><a href="#cta">Early access</a></li>
          </ul>
        </div>
        <div className="foot-col">
          <h5>Company</h5>
          <ul>
            <li><a href="#">About</a></li>
            <li><a href="#">Manifesto</a></li>
            <li><a href="#">Careers</a></li>
            <li><a href="#">Press</a></li>
          </ul>
        </div>
        <div className="foot-col">
          <h5>Legal</h5>
          <ul>
            <li><a href="#">Terms</a></li>
            <li><a href="#">Privacy policy</a></li>
            <li><a href="#">Security</a></li>
            <li><a href="#">Contact</a></li>
          </ul>
        </div>
      </div>
      <div className="foot-bottom">
        <span>© 2026 LIFE · Built with care</span>
        <span>app.livefully.today</span>
      </div>
    </div>
  </footer>
);

window.AICompanion = AICompanion;
window.Results = Results;
window.Privacy = Privacy;
window.FinalCTA = FinalCTA;
window.SiteFooter = Footer;
