// Home page
const { useState: useStateHome, useEffect: useEffectHome, useRef: useRefHome } = React;

// -- Hero with typewriter rotating word --
function HeroSafe({ onQuote, setRoute }) {
  const words = ['a prototype', 'an MVP', 'a team extension', 'an AI agent', 'the thing you sketched'];
  const [idx, setIdx] = useStateHome(0);
  const [shown, setShown] = useStateHome('');
  const [phase, setPhase] = useStateHome('typing'); // typing | holding | deleting

  useEffectHome(() => {
    let t;
    const full = words[idx];
    if (phase === 'typing') {
      if (shown.length < full.length) {
        t = setTimeout(() => setShown(full.slice(0, shown.length + 1)), 55);
      } else {
        t = setTimeout(() => setPhase('holding'), 1600);
      }
    } else if (phase === 'holding') {
      t = setTimeout(() => setPhase('deleting'), 200);
    } else {
      if (shown.length > 0) {
        t = setTimeout(() => setShown(full.slice(0, shown.length - 1)), 28);
      } else {
        setIdx((idx + 1) % words.length);
        setPhase('typing');
      }
    }
    return () => clearTimeout(t);
  }, [shown, phase, idx]);

  return (
    <section className="hero">
      <div className="hero-inner">
        <p className="eyebrow reveal reveal-in">Digital Nepal Solution &middot; est. 2021</p>
        <h1 className="hero-title">
          <span className="d1">Software,</span>{' '}
          <span className="d2">shipped at the speed</span>{' '}
          <span className="d3">AI makes possible.</span>
        </h1>
        <p className="hero-sub">
          We're a small team of builders in Kathmandu — designers, engineers, and thinkers.
          We use AI throughout our process — so you get <em>{shown}</em><span className="caret" /> sooner,
          built by people who still care about the details.
        </p>
        <div className="hero-cta">
          <button className="btn btn-primary btn-lg" onClick={onQuote}>Request a quote</button>
          <button className="btn btn-ghost btn-lg" onClick={() => setRoute('process')}>See how we work &rarr;</button>
        </div>
        <div className="hero-meta mono">
          <span><span className="dot dot-teal" /> Senior engineers</span>
          <span><span className="dot dot-yellow" /> 10+ ships</span>
          <span><span className="dot dot-red" /> 4 yrs in business</span>
        </div>
      </div>
      <div className="hero-art" aria-hidden="true">
        <HeroGrid />
      </div>
    </section>
  );
}

// Ambient grid — cells light up in a slow wave
function HeroGrid() {
  const cols = 14, rows = 9;
  const [tick, setTick] = useStateHome(0);
  useEffectHome(() => {
    const id = setInterval(() => setTick(t => t + 1), 120);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="hero-grid" style={{ gridTemplateColumns: `repeat(${cols}, 1fr)` }}>
      {Array.from({ length: cols * rows }).map((_, i) => {
        const x = i % cols, y = Math.floor(i / cols);
        const wave = Math.sin((x + y) * 0.5 + tick * 0.12) * 0.5 + 0.5;
        const active = wave > 0.82;
        const hue = (x + y) % 3;
        return (
          <div
            key={i}
            className={`hero-cell ${active ? 'on' : ''} hue-${hue}`}
            style={{ opacity: 0.15 + wave * 0.85 }}
          />
        );
      })}
    </div>
  );
}

// -- Three pillars --
function Pillars() {
  const items = [
    { n: '01', t: 'Made by humans, with AI.', b: 'Every product we ship is built by a real team — designers, engineers, thinkers. AI helps us move faster, but the judgment, taste, and care belong to the people.' },
    { n: '02', t: 'One team, end to end.', b: 'You work with the same group from first call to final handover. No hand-offs, no rotating cast. The team that scopes your project is the team that builds it.' },
    { n: '03', t: 'Building the future together.', b: 'We treat your problem like ours. That means telling you what we think, pushing back when it matters, and sticking around long enough to see the thing work.' },
  ];
  return (
    <section className="section pillars">
      <div className="section-head">
        <p className="eyebrow">Why teams pick DNS</p>
        <h2>Software made by <em>humans</em>, with a little help from <em>AI</em>.</h2>
      </div>
      <div className="pillars-grid">
        {items.map((it, i) => (
          <Reveal key={it.n} delay={i * 80}>
            <article className="pillar">
              <div className="pillar-n mono">{it.n}</div>
              <h3>{it.t}</h3>
              <p>{it.b}</p>
            </article>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

// -- Services teaser --
function ServicesTeaser({ setRoute }) {
  const tiles = [
    { tag: 'WEB',    t: 'Custom web apps',          b: 'Next.js, Rails, or Django — whatever fits. We build the thing, not religion-war the stack.', color: 'teal' },
    { tag: 'AI',     t: 'AI agents & automations',  b: 'LLM-powered internal tools that replace spreadsheets, tickets, and tribal knowledge.', color: 'yellow' },
    { tag: 'MVP',    t: 'MVP sprints',              b: '2–6 weeks. Fixed price. One working product at the end — not a pitch deck.', color: 'red' },
    { tag: 'CLOUD',  t: 'Cloud & DevOps',           b: "CI/CD that doesn't break on Fridays. Infra you could hand to anyone.", color: 'teal' },
    { tag: 'DESIGN', t: 'UI/UX design',             b: "Interfaces your users don't have to think about to use correctly.", color: 'yellow' },
    { tag: 'ADVICE', t: 'Consulting',               b: 'A thinking partner in your Slack for the weeks you need one.', color: 'red' },
  ];
  return (
    <section className="section services-teaser">
      <div className="section-head">
        <p className="eyebrow">What we build</p>
        <h2>Eight capabilities. One team owning every engagement.</h2>
      </div>
      <div className="tiles">
        {tiles.map((t, i) => (
          <Reveal key={t.tag} delay={(i % 3) * 70}>
            <article className={`tile tile-${t.color}`} onClick={() => { setRoute('services'); window.scrollTo(0,0); }}>
              <span className="tile-tag mono">[{t.tag}]</span>
              <h3>{t.t}</h3>
              <p>{t.b}</p>
              <span className="tile-arrow">&rarr;</span>
            </article>
          </Reveal>
        ))}
      </div>
      <div className="section-foot">
        <button className="btn btn-ghost" onClick={() => { setRoute('services'); window.scrollTo(0,0); }}>See all services &rarr;</button>
      </div>
    </section>
  );
}

// -- Tech strip --
function TechStrip() {
  const groups = [
    { label: 'FRONTEND', items: ['React', 'Next.js', 'TypeScript', 'Tailwind', 'Vue'] },
    { label: 'BACKEND',  items: ['Node', 'Python', 'Django', 'Rails', 'Go'] },
    { label: 'DATA',     items: ['Postgres', 'Redis', 'Elastic', 'BigQuery'] },
    { label: 'CLOUD',    items: ['AWS', 'GCP', 'Azure', 'Docker', 'Kubernetes'] },
    { label: 'AI',       items: ['OpenAI', 'Anthropic', 'LangChain', 'LlamaIndex', 'pgvector'] },
  ];
  return (
    <Reveal>
      <section className="section tech-strip">
        <p className="eyebrow">Tools of the trade</p>
        <div className="tech-groups">
          {groups.map(g => (
            <div key={g.label} className="tech-group">
              <span className="tech-label mono">{g.label}</span>
              <div className="tech-items">
                {g.items.map(i => <span key={i} className="tech-chip">{i}</span>)}
              </div>
            </div>
          ))}
        </div>
      </section>
    </Reveal>
  );
}

// -- Process preview --
function ProcessPreview({ setRoute }) {
  const steps = [
    { n: '01', t: 'Scope',    d: '3–5 days',  b: 'We listen, ask the uncomfortable questions, and write a plan you can actually read.' },
    { n: '02', t: 'Design',   d: '1–2 weeks', b: 'Interfaces and architecture in parallel. AI drafts, humans decide.' },
    { n: '03', t: 'Build',    d: '2–8 weeks', b: 'Daily demo-able commits. You watch it grow.' },
    { n: '04', t: 'Handover', d: 'ongoing',   b: 'Code, docs, and a team that knows how to run it.' },
  ];
  return (
    <section className="section process-preview">
      <div className="section-head">
        <p className="eyebrow">How a project runs with us</p>
        <h2>Four chapters. No surprises.</h2>
      </div>
      <div className="timeline">
        {steps.map((s, i) => (
          <Reveal key={s.n} delay={i * 70}>
            <div className="tl-step">
              <div className="tl-line"><span className="tl-dot" /></div>
              <div className="tl-body">
                <span className="tl-num mono">{s.n} &middot; {s.d}</span>
                <h3>{s.t}</h3>
                <p>{s.b}</p>
              </div>
            </div>
          </Reveal>
        ))}
      </div>
      <div className="section-foot">
        <button className="btn btn-ghost" onClick={() => { setRoute('process'); window.scrollTo(0,0); }}>Read the full process &rarr;</button>
      </div>
    </section>
  );
}

// -- Manifesto --
function Manifesto() {
  return (
    <Reveal>
      <section className="manifesto">
        <div className="manifesto-inner">
          <p className="eyebrow">Our belief</p>
          <h2>Building the future, <em>together</em>.</h2>
          <p>We're not here to replace people with machines. We're here to make small teams capable of big things — by combining human craft with the tools of our time. The best software is still built by people who care. We just care <em>faster</em> now.</p>
        </div>
      </section>
    </Reveal>
  );
}

// -- Closing CTA --
function ClosingCTA({ onQuote }) {
  return (
    <Reveal>
      <section className="closing">
        <div className="closing-inner">
          <h2>Have something in mind?</h2>
          <p>Tell us about it. We'll come back within a working day with either a plan, a question, or an honest "this isn't a fit."</p>
          <button className="btn btn-primary btn-lg" onClick={onQuote}>Request a quote</button>
        </div>
      </section>
    </Reveal>
  );
}

function HomePage({ onQuote, setRoute }) {
  return (
    <main className="home">
      <HeroSafe onQuote={onQuote} setRoute={setRoute} />
      <Pillars />
      <Manifesto />
      <ServicesTeaser setRoute={setRoute} />
      <TechStrip />
      <ProcessPreview setRoute={setRoute} />
      <ClosingCTA onQuote={onQuote} />
    </main>
  );
}

Object.assign(window, { HomePage });
