/* global React, Icon, CtaBand */
const { useState, useRef, useEffect } = React;

// ─── Candle Wall ───
const CW_MSGS = [
  { from: 'Sarah M.',     to: 'Dad',            text: 'I still set a place at the table for you on Sundays.' },
  { from: 'James',        to: 'Mum',            text: 'You would have loved how tall the kids have grown.' },
  { from: 'Ellie',        to: 'Grandpa',        text: 'I hear your laugh every time I tell one of your jokes.' },
  { from: 'Tom & Rose',   to: 'Nan',            text: 'We named the baby after you. She has your smile.' },
  { from: 'David',        to: 'My brother',     text: 'Not a day goes by. Not one.' },
  { from: 'Claire',       to: 'Mum',            text: 'I became a nurse because of you. I hope you know that.' },
  { from: 'The Johnsons', to: 'Robert',         text: 'The garden is still beautiful. We made sure of it.' },
  { from: 'Priya',        to: 'Grandma',        text: 'I made your recipe yesterday. The whole kitchen smelled like you.' },
  { from: 'Ben',          to: 'Dad',            text: 'I got the job. I wish I could have called you.' },
  { from: 'Anya',         to: 'Mum',            text: 'I still reach for the phone to tell you things.' },
  { from: 'The Williams', to: 'Grandad',        text: 'We scattered your ashes by the sea. You would have approved.' },
  { from: 'Luke',         to: 'My son',         text: 'I write letters I can never send. One day I hope you read them.' },
  { from: 'Maria',        to: 'Papa',           text: 'The world is a quieter place without your stories.' },
  { from: 'Jack',         to: 'Nan',            text: "I still buy your biscuits at the shop. I don't know why." },
  { from: 'Sophie',       to: 'Grandma',        text: 'I wear your ring every single day.' },
  { from: 'Nadia & Sam',  to: 'Our father',     text: 'We watched the game last Sunday. We left your chair empty.' },
  { from: 'Chris',        to: 'Mum',            text: 'You were right about everything. I should have said so sooner.' },
  { from: 'The Patels',   to: 'Rajan',          text: 'Forty years. Not enough. Never enough.' },
  { from: 'Emma',         to: 'My sister',      text: 'I still sleep on my side of the bed.' },
  { from: 'Oliver',       to: 'Dad',            text: 'I finished the book you never got to read. It was brilliant.' },
  { from: 'Grace',        to: 'Grandpa',        text: 'I can still hear your voice when I need to be brave.' },
  { from: 'Marcus',       to: 'Mum',            text: "Your flowers are still growing. I haven't touched them." },
  { from: 'Isabelle',     to: 'Nan',            text: "I baked the cake for Mum's birthday. She cried. We both did." },
  { from: 'Henry',        to: 'My wife',        text: "I made the bed on your side this morning. I don't know why I still do." },
  { from: 'Lena',         to: 'Dad',            text: 'I walked down the aisle alone. But I felt you there.' },
  { from: 'The Kellys',   to: 'Grandma',        text: 'We kept your recipes. We keep making them.' },
  { from: 'Daniel',       to: 'My brother',     text: 'I still argue with you in my head. You still win.' },
  { from: 'Amara',        to: 'Mum',            text: 'I had the baby. A girl. She looks just like you.' },
  { from: 'Patrick',      to: 'Dad',            text: 'I visit on Thursdays. Just like we used to.' },
  { from: 'Zoe',          to: 'Grandad',        text: 'I finally learned to drive. I thought of you the whole time.' },
  { from: 'The Nguyens',  to: 'Our grandfather',text: 'We light a candle for you every Sunday evening.' },
  { from: 'Fiona',        to: 'Mum',            text: "I found your old letters. I've read them every night this month." },
  { from: 'Alex',         to: 'Nan',            text: 'You always said the world would be kind if we were kind first.' },
  { from: 'Harriet',      to: 'My daughter',    text: 'You were only here for nine weeks. But you changed everything.' },
  { from: 'George',       to: 'Dad',            text: 'I finally told Mum I love her. You always said I should.' },
  { from: 'Mia',          to: 'Grandma',        text: 'I kept your old coat. I wear it when it rains.' },
  { from: 'The Robinsons',to: 'Eric',           text: 'There is a hole in everything you used to fill.' },
  { from: 'Jess',         to: 'Mum',            text: 'I passed my exams. I put the certificate next to your photo.' },
];

const CW_POS = [1,3,6,8,11,14,16,19,21,24,27,29,32,35,37,40,43,45,48,51,53,56,59];
const CW_DATA = Array.from({ length: 60 }, (_, i) => {
  const idx = CW_POS.indexOf(i);
  return idx !== -1 ? CW_MSGS[idx] : null;
});

const CW_COLS = 20;

function CandleWall() {
  const [hovered, setHovered] = useState(null);
  const leaveTimer = useRef(null);

  const enter = (i) => { clearTimeout(leaveTimer.current); setHovered(i); };
  const leave = () => { leaveTimer.current = setTimeout(() => setHovered(null), 140); };

  return (
    <section className="cw-section" data-em-surface="ink">
      <div className="cw-head">
        <div className="em-eyebrow">From those who remember</div>
        <h2>Their voices, still reaching.</h2>
        <p>Real messages left by real families — shared with permission. Hover a candle to read one.</p>
      </div>
      <div className="cw-grid">
        {CW_DATA.map((d, i) => {
          const row = Math.floor(i / CW_COLS);
          const col = i % CW_COLS;
          const hRow = hovered !== null ? Math.floor(hovered / CW_COLS) : -1;
          const hCol = hovered !== null ? hovered % CW_COLS : -1;
          const isHov = i === hovered;

          let tx = 0;
          if (!isHov && row === hRow && hovered !== null) {
            const dist = col - hCol;
            const abs = Math.abs(dist);
            if (abs > 0 && abs <= 5) tx = (dist > 0 ? 1 : -1) * (6 - abs) * 5;
          }

          const align = col <= 3 ? 'left' : col >= 17 ? 'right' : 'center';
          const delay = `${(i * 137) % 2200}ms`;

          return (
            <div
              key={i}
              className={'cw-item' + (isHov ? ' is-hov' : '') + (d ? ' has-msg' : '')}
              style={{ transform: isHov ? 'translateY(-12px) scale(1.25)' : tx ? `translateX(${tx}px)` : undefined }}
              onMouseEnter={() => enter(i)}
              onMouseLeave={leave}
              onFocus={d ? () => enter(i) : undefined}
              onBlur={d ? leave : undefined}
              onTouchStart={d ? () => enter(i) : undefined}
              tabIndex={d ? 0 : -1}
              role={d ? 'button' : undefined}
              aria-label={d ? `Message for ${d.to} from ${d.from}` : undefined}
            >
              {isHov && d && (
                <div
                  className={'cw-bubble cw-bubble--' + align}
                  onMouseEnter={() => enter(i)}
                  onMouseLeave={leave}
                >
                  <div className="cw-bubble__to">For {d.to}</div>
                  <p className="cw-bubble__text">"{d.text}"</p>
                  <div className="cw-bubble__from">— {d.from}</div>
                </div>
              )}
              <div className="cw-candle">
                <div className="cw-flame-wrap">
                  <div className="cw-glow" style={{ animationDelay: delay }} />
                  <div className="cw-flame" style={{ animationDelay: delay }} />
                </div>
                <div className="cw-wick" />
                <div className={'cw-body cw-body--' + (i % 3)} />
                <div className="cw-base" />
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

function HomePage({ navigate }) {
  const [lit, setLit] = useState(false);
  const heroRef = useRef(null);
  const candleRef = useRef(null);
  const target = useRef({ x: 0, y: 0 });
  const current = useRef({ x: 0, y: 0 });
  const rafId = useRef(null);

  useEffect(() => {
    const ease = 0.06;
    const tick = () => {
      current.current.x += (target.current.x - current.current.x) * ease;
      current.current.y += (target.current.y - current.current.y) * ease;
      if (candleRef.current) {
        candleRef.current.style.transform =
          `translate(${current.current.x}px, ${current.current.y}px)`;
      }
      rafId.current = requestAnimationFrame(tick);
    };
    rafId.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafId.current);
  }, []);

  const handleMouseMove = (e) => {
    const rect = heroRef.current.getBoundingClientRect();
    target.current.x = e.clientX - rect.left;
    target.current.y = e.clientY - rect.top;
  };

  return (
    <div>
      {/* HERO */}
      <section
        className={`hero${lit ? ' is-lit' : ''}`}
        data-em-surface="ink"
        ref={heroRef}
        onMouseMove={handleMouseMove}
        onMouseEnter={() => setLit(true)}
        onMouseLeave={() => setLit(false)}
      >
        <video className="hero__video" autoPlay muted loop playsInline aria-hidden="true">
          <source src="assets/hero2.mp4" type="video/mp4" />
        </video>
        <div className="hero__overlay" />
        <div className="hero__vignette" />
        <div className="hero__candle" ref={candleRef} />
        <div className="hero__inner">
          <div className="em-eyebrow hero__eyebrow">Your Voice · Your Legacy</div>
          <h1 className="hero__title">
            Your voice.<br />
            Shouldn't disappear.
          </h1>
          <p className="hero__lede">
            A secure, private space to record video messages for the people you love —
            and choose exactly when they receive them.
          </p>
          <div className="hero__actions">
            <button className="btn btn--gold btn--lg" onClick={() => navigate('signup')}>Begin Yours</button>
            <button className="btn btn--outline-gold btn--lg" onClick={() => navigate('features')}>How it works</button>
          </div>
          <div className="hero__quietline">Free for the first hour of recordings · No card needed</div>
        </div>
      </section>

      {/* ABOUT (story block) */}
      <section className="section">
        <div className="container">
          <div className="about-block">
            <div className="about-block__copy" data-reveal>
              <div className="em-eyebrow">About us</div>
              <h2>What if you could still be there… <em>even when you're gone</em>?</h2>
              <p>
                Everlasting Memory is a secure digital space where you record personal video
                messages for the people you love — and choose exactly when they receive them.
              </p>
              <p>
                A birthday you might miss. A wedding you won't be there for. The words you
                meant to say. We make sure your voice is still heard, in your own time.
              </p>
              <p style={{ marginTop: 24 }}>
                <a href="/about/" onClick={(e) => { e.preventDefault(); navigate('about'); }} className="btn--inline">
                  Read our full story →
                </a>
              </p>
            </div>
            <div className="about-block__pillars" data-reveal style={{ '--delay': '160ms' }}>
              <div className="pillar">
                <div className="pillar__num">i.</div>
                <h3>Record what matters</h3>
                <p>Personal video messages for the people you love — at your pace, on your terms. No script required.</p>
              </div>
              <div className="pillar">
                <div className="pillar__num">ii.</div>
                <h3>Choose when it arrives</h3>
                <p>A birthday. A graduation. The day after. You decide who hears what, and when.</p>
              </div>
              <div className="pillar">
                <div className="pillar__num">iii.</div>
                <h3>Pass it down</h3>
                <p>Your story, preserved for the generations who'll wish they'd asked.</p>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* SPLIT PHOTO */}
      <div className="split-photo">
        <div className="split-photo__media">
          <div className="split-photo__img" data-parallax="0.25">
            <img src="assets/lifestyle-1.jpg" alt="An elderly person sitting with a grandchild, sharing a quiet moment together" loading="lazy" />
          </div>
          <div className="split-photo__scrim" />
        </div>
        <div className="split-photo__copy" data-reveal>
          <div className="em-eyebrow">For the moments between</div>
          <figure style={{ margin: 0 }}>
            <blockquote className="split-photo__quote">I kept waiting for the right time to say it. There never was one.</blockquote>
            <figcaption className="split-photo__attr">— Shared by families who use Everlasting Memory</figcaption>
          </figure>
          <p>Every family has unfinished conversations. Everlasting Memory gives you the space to finish them — in your own words, on your own time.</p>
        </div>
      </div>

      {/* WHY IT MATTERS */}
      <section className="section section--ink" data-em-surface="ink" aria-labelledby="why-heading">
        <div className="container">
          <div className="section__head" data-reveal>
            <div className="em-eyebrow">Why it matters</div>
            <h2 id="why-heading" className="em-h1" style={{ fontSize: 48, color: 'var(--em-ivory)' }}>
              Life is unpredictable.<br />Your voice doesn't have to be.
            </h2>
            <p className="em-body-lg" style={{ color: 'var(--em-mist)' }}>
              For the moments you might miss — and the words that should still arrive on time.
            </p>
          </div>
          <div className="scenarios">
            <div className="scenario" data-reveal>
              <div className="scenario__rule" />
              <h3>A <em>birthday</em><br />you might miss.</h3>
              <p>Record now. We'll deliver it on the morning of, in your voice — for every birthday they'll ever have without you.</p>
            </div>
            <div className="scenario" data-reveal style={{ '--delay': '120ms' }}>
              <div className="scenario__rule" />
              <h3>A <em>wedding</em><br />you won't be there for.</h3>
              <p>The toast you would have given. The advice your father would have shared. Saved, scheduled, remembered.</p>
            </div>
            <div className="scenario" data-reveal style={{ '--delay': '240ms' }}>
              <div className="scenario__rule" />
              <h3>The <em>words</em><br />left unsaid.</h3>
              <p>Sometimes a single sentence is everything. Tell them now, in your own voice — they'll hear you when they need it.</p>
            </div>
          </div>
        </div>
      </section>

      {/* TRUST */}
      <section className="trust section" style={{ paddingTop: 96, paddingBottom: 96 }} aria-labelledby="trust-heading">
        <div className="container">
          <div className="trust__grid">
            <div className="trust__head" data-reveal>
              <div className="em-eyebrow">Built on trust</div>
              <h2 id="trust-heading">Your story stays yours.</h2>
            </div>
            <div className="trust__items">
              <div className="trust__item" data-reveal>
                <div className="trust__check"><Icon name="lock" size={14} /></div>
                <div>
                  <h4>End-to-end encrypted</h4>
                  <p>Every recording is encrypted before it leaves your device. We can't watch them. Neither can anyone else.</p>
                </div>
              </div>
              <div className="trust__item" data-reveal style={{ '--delay': '100ms' }}>
                <div className="trust__check"><Icon name="users" size={14} /></div>
                <div>
                  <h4>Only your chosen recipients</h4>
                  <p>You name who receives what. They're verified before any video is unlocked.</p>
                </div>
              </div>
              <div className="trust__item" data-reveal style={{ '--delay': '200ms' }}>
                <div className="trust__check"><Icon name="shield" size={14} /></div>
                <div>
                  <h4>You stay in control</h4>
                  <p>Edit, reschedule, or delete a message at any time. As long as you're here, the keys are yours.</p>
                </div>
              </div>
              <div className="trust__item" data-reveal style={{ '--delay': '300ms' }}>
                <div className="trust__check"><Icon name="heart" size={14} /></div>
                <div>
                  <h4>Held with care</h4>
                  <p>We treat your recordings the way we'd treat our parents'. Quietly, carefully, and forever.</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* PHOTO BAND */}
      <div className="photo-band">
        <div className="photo-band__bg" data-parallax="0.25">
          <img src="assets/lifestyle-2.jpg" alt="Hands cradling a warm cup at a family gathering" loading="lazy" />
        </div>
        <div className="photo-band__overlay" />
        <div className="photo-band__inner" data-reveal>
          <p className="photo-band__quote">"The most important stories are the ones we forget to tell."</p>
          <p className="photo-band__attr">— Shared by families who use Everlasting Memory</p>
          <button className="btn btn--outline-gold" onClick={() => navigate('signup')}>Begin preserving your voice</button>
        </div>
      </div>

      {/* CANDLE WALL */}
      <CandleWall />

      {/* PRICING TEASER */}
      <section className="section section--paper">
        <div className="container">
          <div className="section__head">
            <div className="em-eyebrow">Plans</div>
            <h2 className="em-h1" style={{ fontSize: 48 }}>Honest pricing.<br /><em style={{ color: 'var(--em-antique-gold)', fontWeight: 400 }}>For everyone.</em></h2>
            <p className="em-body-lg">
              Start free. Upgrade only if your story keeps growing. Nothing locked away because you couldn't afford it.
            </p>
          </div>
          <div className="pricing-grid" style={{ maxWidth: 960, margin: '0 auto' }}>
            <PricingPlan
              name="Keepsake"
              price="£0"
              per="forever"
              desc="Start with one memory. That's enough for today."
              feats={['1 hour of recordings', 'Up to 3 recipients', 'Scheduled delivery', 'End-to-end encrypted']}
              cta="Begin free"
              onCta={() => navigate('signup')}
            />
            <PricingPlan
              featured
              badge="Most chosen"
              name="Family"
              price="£8"
              per="per month"
              desc="Enough room for a lifetime of stories — and the people who deserve them."
              feats={['Unlimited recordings', 'Up to 12 recipients', 'Milestone scheduling', 'Shared family library', 'Priority support']}
              cta="Begin Family"
              onCta={() => navigate('signup')}
            />
            <PricingPlan
              name="Legacy"
              price="£24"
              per="per month"
              desc="A complete archive — for the people who want to leave a full story behind."
              feats={['Everything in Family', 'Unlimited recipients', 'Generational handoff', 'Printed memory book', 'Dedicated archivist']}
              cta="Begin Legacy"
              onCta={() => navigate('signup')}
            />
          </div>
          <div style={{ textAlign: 'center', marginTop: 40 }}>
            <a href="/pricing/" onClick={(e) => { e.preventDefault(); navigate('pricing'); }} className="btn--inline" style={{ fontSize: 14 }}>
              Compare every plan →
            </a>
          </div>
        </div>
      </section>

      {/* CLOSING CTA */}
      <CtaBand
        navigate={navigate}
        title="Because tomorrow isn't guaranteed —<br/>but your <em>voice</em> can be."
        body="Start with one memory. That's enough for today."
      />
    </div>
  );
}

function PricingPlan({ featured, badge, name, price, per, desc, feats, cta, onCta }) {
  return (
    <div className={"plan" + (featured ? " plan--featured" : "")}>
      {badge && <div className="plan__badge">{badge}</div>}
      <div className="plan__name">{name}</div>
      <div className="plan__price-row">
        <div className="plan__price">{price}</div>
        <div className="plan__per">{per}</div>
      </div>
      <p className="plan__desc">{desc}</p>
      <ul className="plan__feats">
        {feats.map((f, i) => (
          <li className="plan__feat" key={i}>
            <Icon name="check" size={16} />
            <span>{f}</span>
          </li>
        ))}
      </ul>
      <div className="plan__cta">
        <button
          className={"btn " + (featured ? "btn--gold" : "btn--outline-ink")}
          style={{ width: '100%', justifyContent: 'center' }}
          onClick={onCta}
        >{cta}</button>
      </div>
    </div>
  );
}

Object.assign(window, { HomePage, PricingPlan });
