const { useState, useEffect, useRef } = React;

// === Hooks ===
function useScrollReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal, .reveal-stagger');
    const seedVisible = () => {
      const vh = window.innerHeight || document.documentElement.clientHeight;
      els.forEach((el) => {
        const r = el.getBoundingClientRect();
        if (r.top < vh * 0.9 && r.bottom > 0) el.classList.add('in');
      });
    };
    requestAnimationFrame(seedVisible);
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

function useMouseGlow(ref) {
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const move = (e) => {
      const r = el.getBoundingClientRect();
      el.style.setProperty('--mx', `${e.clientX - r.left}px`);
      el.style.setProperty('--my', `${e.clientY - r.top}px`);
    };
    el.addEventListener('mousemove', move);
    return () => el.removeEventListener('mousemove', move);
  }, [ref]);
}

// === Hero product mock - exactly per screenshot ===
function HeroMock() {
  const [stage, setStage] = useState(0); // 0 idle, 1 activated, 2 opened, 3 filled, 4 verified, 5 logged in
  const [emailTyped, setEmailTyped] = useState('');
  const [pwTyped, setPwTyped] = useState('');
  const wrapRef = useRef(null);

  const targetEmail = 'ava@example.com';
  const targetPw = '••••••••••••';

  // 3D tilt
  useEffect(() => {
    const el = wrapRef.current;
    if (!el) return;
    let rafId;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const cx = r.left + r.width / 2;
      const cy = r.top + r.height / 2;
      const dx = (e.clientX - cx) / r.width;
      const dy = (e.clientY - cy) / r.height;
      cancelAnimationFrame(rafId);
      rafId = requestAnimationFrame(() => {
        el.style.transform = `perspective(1400px) rotateY(${dx * 3.5}deg) rotateX(${-dy * 3.5}deg) translateY(${-dy * 3}px)`;
      });
    };
    const onLeave = () => { el.style.transform = ''; };
    el.addEventListener('mousemove', onMove);
    el.addEventListener('mouseleave', onLeave);
    return () => {
      el.removeEventListener('mousemove', onMove);
      el.removeEventListener('mouseleave', onLeave);
      cancelAnimationFrame(rafId);
    };
  }, []);

  // Auto-loop animation
  useEffect(() => {
    let cancelled = false;
    let timers = [];

    function run() {
      setStage(0);
      setEmailTyped('');
      setPwTyped('');

      const t = (ms, fn) => timers.push(setTimeout(() => { if (!cancelled) fn(); }, ms));

      // 1) Activate flow @ 900ms
      t(900, () => setStage(1));
      // 2) Open saved login URL @ 1700ms
      t(1700, () => setStage(2));
      // 3) Type email
      const emailStart = 2300;
      for (let i = 1; i <= targetEmail.length; i++) {
        t(emailStart + i * 45, () => setEmailTyped(targetEmail.slice(0, i)));
      }
      const afterEmail = emailStart + targetEmail.length * 45 + 200;
      // 4) Type password
      for (let i = 1; i <= targetPw.length; i++) {
        t(afterEmail + i * 50, () => setPwTyped(targetPw.slice(0, i)));
      }
      const afterPw = afterEmail + targetPw.length * 50 + 300;
      // 5) Fill credentials done
      t(afterPw, () => setStage(3));
      // 6) Submit and verify success
      t(afterPw + 900, () => setStage(4));
      // 7) Logged in
      t(afterPw + 1500, () => setStage(5));

      // restart
      t(afterPw + 6000, run);
    }

    run();
    return () => { cancelled = true; timers.forEach(clearTimeout); };
  }, []);

  const checks = [
    { idx: 2, label: 'Open saved login URL' },
    { idx: 3, label: 'Fill credentials' },
    { idx: 4, label: 'Submit and verify success' },
  ];

  return (
    <div ref={wrapRef} className="window float-mount" style={{ transition: 'transform 0.4s cubic-bezier(0.2,0.8,0.2,1)' }}>
      <div className="win-bar">
        <div className="win-dots">
          <span className="win-dot r"></span>
          <span className="win-dot y"></span>
          <span className="win-dot g"></span>
        </div>
        <div className="win-url">secure.example.com/login</div>
      </div>
      <div className="win-body">
        {/* Left panel: Flow Manager */}
        <div className="panel panel-flow">
          <div className="panel-head">
            <div>
              <div className="panel-title">Flow Manager</div>
              <div className="panel-sub">Login automation</div>
            </div>
            <span className={`tag ${stage >= 5 ? 'tag-complete' : 'tag-pending'}`}>
              {stage >= 5 ? 'Complete' : stage >= 1 ? 'Running' : 'Idle'}
            </span>
          </div>

          <button className={`activate-btn ${stage >= 1 ? 'is-active' : ''}`}>
            <span className="ic">
              {stage >= 1 && stage < 5 ? (
                <span className="spinner"></span>
              ) : stage >= 5 ? (
                <Icons.Check size={14} />
              ) : (
                <Icons.Play />
              )}
            </span>
            <span>{stage >= 5 ? 'Flow Complete' : stage >= 1 ? 'Running flow…' : 'Activate flow'}</span>
          </button>

          <div className="check-list">
            {checks.map((c) => (
              <div key={c.idx} className={`check-item ${stage >= c.idx ? 'done' : stage === c.idx - 1 ? 'pending' : 'idle'}`}>
                <span className="check-ic">
                  {stage >= c.idx ? <Icons.Check size={11} /> : stage === c.idx - 1 ? <span className="dot-pulse" /> : null}
                </span>
                <span className="check-text">{c.label}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Right panel: Example Site */}
        <div className="panel panel-site">
          <div className="panel-head">
            <div>
              <div className="panel-title">Example Site</div>
              <div className="panel-sub">Customer login</div>
            </div>
            <span className="tag tag-demo">Demo</span>
          </div>

          <div className="form-field">
            <div className="form-lbl">EMAIL</div>
            <div className="form-input">
              <span className="form-val">{emailTyped}</span>
              {emailTyped && emailTyped.length < targetEmail.length && <span className="form-caret" />}
            </div>
          </div>

          <div className="form-field">
            <div className="form-lbl">PASSWORD</div>
            <div className="form-input">
              <span className="form-val mono">{pwTyped}</span>
              {pwTyped && pwTyped.length < targetPw.length && <span className="form-caret" />}
            </div>
          </div>

          <button className={`continue-btn ${stage === 4 ? 'is-loading' : ''} ${stage >= 5 ? 'is-done' : ''}`}>
            {stage === 4 ? 'Signing in…' : 'Continue'}
          </button>

          <div className={`logged-in ${stage >= 5 ? 'is-on' : ''}`}>
            <span className="li-check"><Icons.Check size={12} /></span>
            <div className="li-text">
              <div className="li-ttl">Logged in</div>
              <div className="li-sub">The flow automatically logged you in.</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// === Hero ===
function Hero() {
  return (
    <section className="hero">
      <div className="container-wide">
        <div className="hero-grid">
          <div className="hero-copy reveal">
            <h1 className="display">Passworthy Logins and Flows</h1>
            <p className="lead">
              Save passwords, private phone lines, and account details in one encrypted vault. Share access with people you trust, and let Passworthy handle repetitive login forms.
            </p>
            <div className="hero-cta">
              <a href="https://passworthy.app/public/identity/new" className="btn btn-primary">
                Get Started Today
                <span className="arrow"><Icons.Arrow /></span>
              </a>
            </div>
          </div>
          <div className="hero-mock reveal" style={{ transitionDelay: '0.15s' }}>
            <HeroMock />
          </div>
        </div>
      </div>
    </section>
  );
}

// === How it works ===
function HowItWorks() {
  return (
    <section className="section" id="how">
      <div className="container-wide">
        <div className="split">
          <div className="split-copy reveal">
            <span className="eyebrow pill">How it works</span>
            <h2 className="h2">Start with a secure credentials vault. Automation exactly where it helps.</h2>
            <p className="lead">
              Passworthy works as a secure password manager first: saved credentials, account notes, phone-backed verification details, and the context you need to get back into an account later.
            </p>
            <p className="lead">
              For sites with extra steps, a saved flow can open the right page, fill what it knows, click through the routine parts, and confirm the login worked.
            </p>
          </div>
          <div className="step-stack reveal-stagger">
            <StepRow num="1" title="Save the account once" desc="Keep the password, login URL, recovery details, and private phone line together in your encrypted vault." />
            <StepRow num="2" title="Share access when needed" desc="Give family, friends, or collaborators access to the accounts they help manage without sending passwords over chat." />
            <StepRow num="3" title="Let flows do the clicking" desc="When a login has multiple pages, waits, or checks, Passworthy can make it easier for you." />
          </div>
        </div>
      </div>
    </section>
  );
}

function StepRow({ num, title, desc }) {
  const ref = useRef(null);
  useMouseGlow(ref);
  return (
    <div ref={ref} className="step-row">
      <div className="step-num">{num}</div>
      <div>
        <div className="step-ttl">{title}</div>
        <div className="step-desc">{desc}</div>
      </div>
    </div>
  );
}

// === Everything included tiles ===
const TILES = [
  { icon: Icons.PlayTile,    title: 'Convenient Login Flows', desc: 'Run saved sign-in paths for accounts with multi-page forms, extra waits, or repeatable account actions.' },
  { icon: Icons.VaultTile,   title: 'Password Vault',         desc: 'Store passwords, account details, notes, and recovery context inside a zero-knowledge encrypted vault.' },
  { icon: Icons.ShareTile,   title: 'Account Sharing',        desc: 'Share account access with family, friends, or teammates so the right people can get in when they need to.' },
  { icon: Icons.PhoneTile,   title: 'Private Phone Lines',    desc: 'Attach a private number to accounts that require SMS, voice, or phone-backed recovery.' },
  { icon: Icons.LockTile,    title: 'Encrypted by Default',   desc: 'Your saved credentials are sealed before they leave your device, so Passworthy cannot read them server-side.' },
  { icon: Icons.BrowserTile, title: 'Browser Extension',      desc: 'Use Passworthy from the browser to fill passwords, launch saved flows, and keep account details close while you sign in.' },
];

function Tile({ icon: Icon, title, desc }) {
  const ref = useRef(null);
  useMouseGlow(ref);
  return (
    <div ref={ref} className="tile">
      <div className="tile-icon"><Icon /></div>
      <h4 className="tile-title">{title}</h4>
      <p className="tile-desc">{desc}</p>
    </div>
  );
}

function Everything() {
  return (
    <section className="section" id="features">
      <div className="container-wide">
        <div className="center reveal">
          <span className="eyebrow pill">Everything included</span>
          <h2 className="h2" style={{ marginTop: 20 }}>Passwords, sharing, phone lines, and sign-in flows in one place.</h2>
          <p className="lead center-lead">
            Passworthy keeps the account record useful after the password is saved, so getting in yourself or helping someone else get in feels straightforward.
          </p>
        </div>
        <div className="tile-grid reveal-stagger">
          {TILES.map((t, i) => <Tile key={i} {...t} />)}
        </div>
      </div>
    </section>
  );
}

// === Phone lines section ===
function PhoneCard() {
  const targetPhone = '(319) 321-8807';
  const [phone, setPhone] = useState(targetPhone);
  const [pulse, setPulse] = useState(false);

  useEffect(() => {
    let cancelled = false;
    let timers = [];
    function loop() {
      setPhone('');
      setPulse(false);
      targetPhone.split('').forEach((_, i) => {
        timers.push(setTimeout(() => { if (!cancelled) setPhone(targetPhone.slice(0, i + 1)); }, 500 + i * 55));
      });
      timers.push(setTimeout(() => { if (!cancelled) setPulse(true); }, 500 + targetPhone.length * 55 + 200));
      timers.push(setTimeout(() => { if (!cancelled) loop(); }, 500 + targetPhone.length * 55 + 6000));
    }
    loop();
    return () => { cancelled = true; timers.forEach(clearTimeout); };
  }, []);

  return (
    <div className="phone-card">
      <div className="phone-head">
        <span className="phone-lbl">Example Line</span>
        <span className={`phone-badge ${pulse ? 'pulse-once' : ''}`}>
          <span className="dot"></span>
          Provisioned
        </span>
      </div>
      <div className="phone-number">
        {phone || '\u00A0'}
        {phone.length < targetPhone.length && <span className="phone-caret" />}
      </div>
      <div className="phone-chips">
        <div className="chip">
          <div className="chip-val">Accepted</div>
          <div className="chip-lbl">SMS</div>
        </div>
        <div className="chip">
          <div className="chip-val">Ready</div>
          <div className="chip-lbl">Codes</div>
        </div>
        <div className="chip">
          <div className="chip-val">Linked</div>
          <div className="chip-lbl">Vault</div>
        </div>
      </div>
      <div className="phone-note">
        <div className="phone-note-ttl">Saved with Example Site</div>
        <div className="phone-note-desc">The number, passwords, and recovery details stay together for the next login or handoff.</div>
      </div>
    </div>
  );
}

function PhoneLines() {
  return (
    <section className="section" id="phone">
      <div className="container-wide">
        <div className="verify-split">
          <div className="verify-copy reveal">
            <span className="eyebrow pill">Co-starring: phone lines</span>
            <h2 className="h2" style={{ marginTop: 20 }}>Keep phone requirements with the account.</h2>
            <p className="lead">
              Some services still ask for a phone number for signups, login codes, or recovery. Passworthy keeps that number attached to the account record instead of scattering it across texts, screenshots, and notes.
            </p>
            <ul className="bullets">
              <li>
                <span className="bullet-ic"><Icons.PhoneSmall /></span>
                <span><strong>Less exposure.</strong> Give services a dedicated number instead of your personal one.</span>
              </li>
              <li>
                <span className="bullet-ic"><Icons.KeySmall /></span>
                <span><strong>Verification support.</strong> Keep SMS and voice requirements tied to the login that needs them.</span>
              </li>
              <li>
                <span className="bullet-ic"><Icons.ShareSmall /></span>
                <span><strong>Easier handoff.</strong> Shared account access can include the phone context someone needs to sign in.</span>
              </li>
            </ul>
          </div>
          <div className="reveal" style={{ transitionDelay: '0.15s' }}>
            <PhoneCard />
          </div>
        </div>
      </div>
    </section>
  );
}

// === Privacy section ===
function Privacy() {
  return (
    <section className="section privacy-section" id="privacy">
      <div className="container-wide">
        <div className="privacy-card reveal">
          <div className="privacy-left">
            <span className="eyebrow pill">Built for privacy</span>
            <h2 className="h2" style={{ marginTop: 20 }}>Your data stays yours.</h2>
            <p className="lead" style={{ marginTop: 20 }}>
              Passworthy uses zero-knowledge encryption so your vault is sealed on your device before it ever reaches our servers. Passwords, phone lines, and shared account records stay under your control.
            </p>
            <div className="privacy-tags">
              <span className="ptag">Zero-knowledge system</span>
              <span className="ptag">Encrypted account data</span>
              <span className="ptag">Controlled sharing</span>
            </div>
          </div>
          <div className="privacy-right reveal-stagger">
            <PillarCard icon={<Icons.LockOpen />} title="Zero knowledge" desc="We cannot see your saved credentials." />
            <PillarCard icon={<Icons.ShieldCheck />} title="Flow-safe" desc="Automation runs from your trusted client." accent />
            <PillarCard icon={<Icons.People />} title="Shareable" desc="Access can be shared without putting passwords into messages." />
          </div>
        </div>
      </div>
    </section>
  );
}

function PillarCard({ icon, title, desc, accent }) {
  const ref = useRef(null);
  useMouseGlow(ref);
  return (
    <div ref={ref} className={`pcard ${accent ? 'pcard-accent' : ''}`}>
      <div className="pcard-icon">{icon}</div>
      <div className="pcard-title">{title}</div>
      <div className="pcard-desc">{desc}</div>
    </div>
  );
}

// === Header ===
function useNavScroll() {
  useEffect(() => {
    const nav = document.querySelector('.site-header');
    if (!nav) return;
    let lastY = window.scrollY;
    let ticking = false;

    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        const y = window.scrollY;
        const delta = y - lastY;

        if (y > 16) nav.classList.add('scrolled');
        else nav.classList.remove('scrolled');

        // Always visible near the top of the page
        if (y < 80) {
          nav.classList.remove('is-hidden');
        } else if (delta > 4) {
          // scrolling down → hide
          nav.classList.add('is-hidden');
        } else if (delta < -4) {
          // scrolling up → show
          nav.classList.remove('is-hidden');
        }

        lastY = y;
        ticking = false;
      });
    };

    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
}

function smoothScrollTo(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const top = el.getBoundingClientRect().top + window.scrollY - 80;
  window.scrollTo({ top, behavior: 'smooth' });
}

function Header() {
  useNavScroll();
  const items = [
    { label: 'How it works', id: 'how' },
    { label: 'Everything included', id: 'features' },
    { label: 'Phone lines', id: 'phone' },
    { label: 'Privacy', id: 'privacy' },
  ];
  return (
    <header className="site-header">
      <div className="header-inner">
        <a
          href="#top"
          className="brand"
          onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); }}
          aria-label="Passworthy — to top"
        >
          <img src="/assets/passworthy-mark.png" alt="" className="brand-mark" />
          <span className="brand-word">Passworthy</span>
        </a>
        <nav className="header-nav">
          {items.map((it) => (
            <a
              key={it.id}
              href={`#${it.id}`}
              onClick={(e) => { e.preventDefault(); smoothScrollTo(it.id); }}
            >
              {it.label}
            </a>
          ))}
        </nav>
        <div class="header-actions">
        <a
          href="https://passworthy.app/public/identity/new"
          className="btn btn-primary header-cta"
        >
          Get Started
          <span className="arrow"><Icons.Arrow /></span>
        </a>
        <a href="https://passworthy.app/public/identity/login"><span class="header-signin">Sign In</span></a>
        </div>
      </div>
    </header>
  );
}

// === Footer ===
function Footer() {
  return (
    <footer className="site-footer">
      <div className="container-wide footer-inner">
        <a
          href="#top"
          className="brand brand-sm"
          onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); }}
        >
          <img src="/assets/passworthy-mark.png" alt="" className="brand-mark" />
          <span className="brand-word">Passworthy</span>
        </a>
        <span className="footer-tag">Stronger passwords. Safer digital life.</span>
        <span className="footer-meta">© {new Date().getFullYear()} Passworthy</span>
      </div>
    </footer>
  );
}

// === App ===
function App() {
  useScrollReveal();
  return (
    <div className="world" id="top">
      <div className="mesh">
        <div className="blob b3"></div>
        <div className="blob b4"></div>
        <div className="blob b5"></div>
      </div>
      <div className="veil"></div>
      <div className="grid-overlay"></div>
      <Header />
      <Hero />
      <HowItWorks />
      <Everything />
      <PhoneLines />
      <Privacy />
      <Footer />
      <div className="noise"></div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
