// Home page — generative direction (animated flow-field hero, live inference terminal,
// animated proof bars, dark gradient process rail, gradient CTA).
const { useState: useStateH, useEffect: useEffectH, useRef: useRefH } = React;

const SERVICES_DATA = [
  {
    n: "01",
    title: "AI Strategy",
    body: "Before we build anything, we sit with your leadership and your operations and find the places AI actually moves the needle. You leave the engagement with a short, ordered plan in plain language — what to do first, what to wait on, and what's not worth doing at all.",
    keywords: ["opportunity mapping", "roadmaps", "ROI modeling"],
  },
  {
    n: "02",
    title: "Data Foundations",
    body: "Most AI projects don't fail at the model — they fail at the data. We get your information clean, connected, and ready to use: pipelines wired to your real systems, documents indexed for retrieval, and the privacy and access rules built in from the start.",
    keywords: ["data pipelines", "governance", "vector indexes"],
  },
  {
    n: "03",
    title: "Custom Models",
    body: "Off-the-shelf AI is a starting point, not a strategy. We tune and train models on your data, your workflows, and your customers — so the result sounds like your business, not a generic chatbot.",
    keywords: ["fine-tuning", "private data", "evaluation"],
  },
  {
    n: "04",
    title: "RAG Systems",
    body: "Your company already knows things — in contracts, in records, in years of internal documents. We turn that knowledge into a system anyone on your team can ask, in plain English, with sources attached.",
    keywords: ["knowledge bases", "search", "grounded answers"],
  },
  {
    n: "05",
    title: "Agent Deployment",
    body: "AI agents that actually do the work — drafting, reviewing, scheduling, replying — inside the tools your team already uses. Built carefully, with humans in the loop where it matters.",
    keywords: ["automation", "workflows", "human-in-loop"],
  },
  {
    n: "06",
    title: "Project Delivery",
    body: "Whatever the AI project is — we scope it, build it, ship it, and train your team to run it. One studio, one team, end to end. You get a working product, not a 200-slide deck.",
    keywords: ["end-to-end build", "training", "ownership"],
  },
];

const PROCESS_DATA = [
  { phase: "I", label: "Listen", body: "We start by understanding your business — your customers, your bottlenecks, the parts of the day your team would happily hand to a machine. No frameworks, just questions." },
  { phase: "II", label: "Build", body: "Within weeks you have something working: a real product against your real data, hooked into the tools your team already uses. Small, tight feedback loops — not a year-long roadmap." },
  { phase: "III", label: "Ship", body: "We harden it for production: reliability, monitoring, security, and the careful work of making sure the AI says \"I don't know\" when it shouldn't be guessing." },
  { phase: "IV", label: "Hand off", body: "You own it. The code, the model, the documentation, the playbook. Your team is trained to extend it — and we're a phone call away when you want us back." },
];

// Flow-field particle hero. Particles drift through a 2D noise vector field
// and inherit color from the brand gradient based on their position.
function FlowFieldCanvas() {
  const canvasRef = useRefH(null);

  useEffectH(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    let raf, w, h, dpr;
    let particles = [];

    const stops = [
      { p: 0.00, c: [184, 75, 201] },
      { p: 0.25, c: [230, 74, 155] },
      { p: 0.55, c: [110, 122, 224] },
      { p: 0.80, c: [79, 168, 232] },
      { p: 1.00, c: [95, 200, 232] },
    ];
    const sampleGrad = (t) => {
      t = Math.max(0, Math.min(1, t));
      for (let i = 1; i < stops.length; i++) {
        if (t <= stops[i].p) {
          const a = stops[i - 1], b = stops[i];
          const k = (t - a.p) / (b.p - a.p);
          return [
            Math.round(a.c[0] + (b.c[0] - a.c[0]) * k),
            Math.round(a.c[1] + (b.c[1] - a.c[1]) * k),
            Math.round(a.c[2] + (b.c[2] - a.c[2]) * k),
          ];
        }
      }
      return stops[stops.length - 1].c;
    };

    const noise = (x, y, t) => {
      return (
        Math.sin(x * 0.0042 + t * 0.0003) * 0.55 +
        Math.cos(y * 0.0048 - t * 0.00025) * 0.55 +
        Math.sin((x + y) * 0.0026 + t * 0.0002) * 0.4
      );
    };

    const resize = () => {
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      w = canvas.clientWidth;
      h = canvas.clientHeight;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      const target = Math.floor((w * h) / 2400);
      particles = new Array(target).fill(0).map(() => ({
        x: Math.random() * w,
        y: Math.random() * h,
        life: Math.random() * 200,
        maxLife: 180 + Math.random() * 220,
        speed: 0.6 + Math.random() * 1.4,
      }));
    };

    resize();
    window.addEventListener("resize", resize);

    const start = performance.now();
    const tick = (now) => {
      const t = now - start;

      ctx.fillStyle = "rgba(10, 9, 18, 0.07)";
      ctx.fillRect(0, 0, w, h);

      ctx.globalCompositeOperation = "lighter";

      for (const p of particles) {
        const angle = noise(p.x, p.y, t) * Math.PI * 2;
        const vx = Math.cos(angle) * p.speed;
        const vy = Math.sin(angle) * p.speed;
        p.x += vx;
        p.y += vy;
        p.life += 1;

        const colorT = (p.x / w + Math.sin(t * 0.0001 + p.y * 0.001) * 0.1 + 1) % 1;
        const [r, g, b] = sampleGrad(colorT);
        const lifeFade = 1 - Math.abs(p.life / p.maxLife - 0.5) * 2;
        const alpha = 0.55 * Math.max(0, lifeFade);

        ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${alpha})`;
        ctx.beginPath();
        ctx.arc(p.x, p.y, 1.1, 0, Math.PI * 2);
        ctx.fill();

        if (p.life > p.maxLife || p.x < -20 || p.x > w + 20 || p.y < -20 || p.y > h + 20) {
          p.x = Math.random() * w;
          p.y = Math.random() * h;
          p.life = 0;
          p.maxLife = 180 + Math.random() * 220;
          p.speed = 0.6 + Math.random() * 1.4;
        }
      }

      ctx.globalCompositeOperation = "source-over";
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", resize);
    };
  }, []);

  return <canvas ref={canvasRef} className="flowfield-canvas" />;
}

const TERMINAL_SCENARIOS = [
  {
    title: "sarmadi · workflow audit",
    lines: [
      { tag: "input", text: "What's slowing my team down?" },
      { tag: "thinking", text: "scanning workflows…" },
      { tag: "thinking", text: "matching against patterns…" },
      { tag: "out", text: "Contract review · 11 hrs/week" },
      { tag: "out", text: "Vendor intake · 6 hrs/week" },
      { tag: "out", text: "Status reporting · 4 hrs/week" },
      { tag: "done", text: "21 hrs/week recoverable." },
    ],
  },
  {
    title: "sarmadi · contract agent",
    lines: [
      { tag: "input", text: "Review this MSA for risk." },
      { tag: "thinking", text: "parsing 47 pages…" },
      { tag: "thinking", text: "checking against playbook…" },
      { tag: "out", text: "§4.2 · indemnity uncapped" },
      { tag: "out", text: "§7.1 · auto-renewal, 90-day notice" },
      { tag: "out", text: "§11 · governing law mismatch" },
      { tag: "done", text: "3 issues flagged · 6 min." },
    ],
  },
  {
    title: "sarmadi · knowledge base",
    lines: [
      { tag: "input", text: "What's our refund policy for B2B?" },
      { tag: "thinking", text: "retrieving from 8,412 docs…" },
      { tag: "thinking", text: "ranking sources…" },
      { tag: "out", text: "Policy v3.2 · §B2B-Refunds" },
      { tag: "out", text: "Net-30 prorated · within 60 days" },
      { tag: "out", text: "Cited: ops-handbook.pdf p.47" },
      { tag: "done", text: "Answered with sources." },
    ],
  },
  {
    title: "sarmadi · intake triage",
    lines: [
      { tag: "input", text: "New patient · headache, 3 days." },
      { tag: "thinking", text: "checking history…" },
      { tag: "thinking", text: "applying triage rules…" },
      { tag: "out", text: "Severity · moderate" },
      { tag: "out", text: "Suggested · same-day visit" },
      { tag: "out", text: "Flag · prior migraine pattern" },
      { tag: "done", text: "Routed to Dr. Chen." },
    ],
  },
  {
    title: "sarmadi · listing agent",
    lines: [
      { tag: "input", text: "Draft listing · 4BR colonial, Sugar Land." },
      { tag: "thinking", text: "pulling comps…" },
      { tag: "thinking", text: "matching brand voice…" },
      { tag: "out", text: "Headline · drafted" },
      { tag: "out", text: "Description · 312 words" },
      { tag: "out", text: "Tags · 14 generated" },
      { tag: "done", text: "Ready for review · 41 sec." },
    ],
  },
  {
    title: "sarmadi · ROI model",
    lines: [
      { tag: "input", text: "Pilot ROI for AI claims review?" },
      { tag: "thinking", text: "ingesting last 12 months…" },
      { tag: "thinking", text: "modeling sensitivity…" },
      { tag: "out", text: "Cycle time · −68%" },
      { tag: "out", text: "Error rate · −31%" },
      { tag: "out", text: "Annualized · $2.4M" },
      { tag: "done", text: "Payback · 4.2 months." },
    ],
  },
  {
    title: "sarmadi · support agent",
    lines: [
      { tag: "input", text: "Order #88421 · refund status?" },
      { tag: "thinking", text: "pulling order history…" },
      { tag: "thinking", text: "checking policy…" },
      { tag: "out", text: "Delivered · 3 days late" },
      { tag: "out", text: "Eligible · store credit + 10%" },
      { tag: "out", text: "Reply drafted · empathic tone" },
      { tag: "done", text: "Resolved · 0 escalations." },
    ],
  },
  {
    title: "sarmadi · compliance check",
    lines: [
      { tag: "input", text: "Review ad copy for compliance." },
      { tag: "thinking", text: "scanning against FINRA rules…" },
      { tag: "thinking", text: "cross-checking disclosures…" },
      { tag: "out", text: "§3 · 'guaranteed returns' flagged" },
      { tag: "out", text: "Backtest disclaimer · missing" },
      { tag: "out", text: "Suggested fix · drafted" },
      { tag: "done", text: "2 issues · approved with edits." },
    ],
  },
  {
    title: "sarmadi · demand forecast",
    lines: [
      { tag: "input", text: "Forecast SKU demand · next 30 days." },
      { tag: "thinking", text: "weighting seasonality + promos…" },
      { tag: "thinking", text: "blending 3 models…" },
      { tag: "out", text: "SKU-4421 · +18% (back-to-school)" },
      { tag: "out", text: "SKU-9907 · −24% (cycle end)" },
      { tag: "out", text: "SKU-2210 · steady" },
      { tag: "done", text: "Reorder list · ready." },
    ],
  },
  {
    title: "sarmadi · lead routing",
    lines: [
      { tag: "input", text: "New inbound lead · qualify and route." },
      { tag: "thinking", text: "enriching firmographics…" },
      { tag: "thinking", text: "scoring intent signals…" },
      { tag: "out", text: "240-employee SaaS · ICP match" },
      { tag: "out", text: "Pricing-page intent · 87/100" },
      { tag: "out", text: "Champion likely · VP Eng" },
      { tag: "done", text: "Routed · enterprise SDR." },
    ],
  },
  {
    title: "sarmadi · code review",
    lines: [
      { tag: "input", text: "Review PR #2341 · auth refactor." },
      { tag: "thinking", text: "parsing diff…" },
      { tag: "thinking", text: "checking patterns…" },
      { tag: "out", text: "2 SQL queries · unparameterized" },
      { tag: "out", text: "Missing rate-limit · /reset" },
      { tag: "out", text: "Test coverage · 71% → 89%" },
      { tag: "done", text: "4 comments posted." },
    ],
  },
  {
    title: "sarmadi · meeting brief",
    lines: [
      { tag: "input", text: "Brief me on the 3pm with Acme." },
      { tag: "thinking", text: "pulling thread + CRM…" },
      { tag: "thinking", text: "summarizing context…" },
      { tag: "out", text: "Last touch · 11 days ago" },
      { tag: "out", text: "Open issue · pricing escalation" },
      { tag: "out", text: "Champion · Sarah Patel, VP Ops" },
      { tag: "done", text: "1-pager · ready." },
    ],
  },
];

function ThinkingTerminal() {
  const [scenarioIdx, setScenarioIdx] = useStateH(() => Math.floor(Math.random() * TERMINAL_SCENARIOS.length));
  const scenario = TERMINAL_SCENARIOS[scenarioIdx];
  const lines = scenario.lines;
  const [shown, setShown] = useStateH(0);
  const [chars, setChars] = useStateH(0);

  useEffectH(() => {
    if (shown >= lines.length) {
      const reset = setTimeout(() => {
        let next;
        do { next = Math.floor(Math.random() * TERMINAL_SCENARIOS.length); }
        while (next === scenarioIdx && TERMINAL_SCENARIOS.length > 1);
        setScenarioIdx(next);
        setShown(0);
        setChars(0);
      }, 3500);
      return () => clearTimeout(reset);
    }
    const current = lines[shown].text;
    if (chars < current.length) {
      const t = setTimeout(() => setChars(chars + 1), 22 + Math.random() * 30);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => { setShown(shown + 1); setChars(0); }, 380);
    return () => clearTimeout(t);
  }, [shown, chars, scenarioIdx]);

  return (
    <div className="thinking-term">
      <div className="thinking-term-bar">
        <span className="thinking-term-dot" style={{ background: "#FF5F57" }}></span>
        <span className="thinking-term-dot" style={{ background: "#FEBC2E" }}></span>
        <span className="thinking-term-dot" style={{ background: "#28C840" }}></span>
        <span className="thinking-term-title">{scenario.title}</span>
      </div>
      <div className="thinking-term-body">
        {lines.slice(0, shown).map((l, i) => (
          <div key={i} className={`tt-line tt-${l.tag}`}>
            <span className="tt-tag">{l.tag}</span>
            <span className="tt-text">{l.text}</span>
          </div>
        ))}
        {shown < lines.length && (
          <div className={`tt-line tt-${lines[shown].tag}`}>
            <span className="tt-tag">{lines[shown].tag}</span>
            <span className="tt-text">
              {lines[shown].text.slice(0, chars)}
              <span className="tt-caret"></span>
            </span>
          </div>
        )}
      </div>
    </div>
  );
}

function HeroGenerative() {
  return (
    <section className="hero-gen">
      <FlowFieldCanvas />
      <div className="hero-gen-vignette"></div>
      <div className="container hero-gen-inner">
        <div className="hero-gen-grid">
          <div className="hero-gen-left">
            <div className="eyebrow eyebrow-dot reveal" style={{ color: "rgba(255,255,255,0.6)" }}>
              Sarmadi LLC — Artificial Intelligence
            </div>
            <h1 className="display reveal reveal-delay-1" style={{ fontSize: "clamp(48px, 8.2vw, 138px)", margin: "32px 0 0", lineHeight: 0.94, color: "#fff" }}>
              Compete like a<br/>
              <em className="display-italic gradient-text">tech-native</em><br/>
              company.
            </h1>
            <p className="hero-gen-lede reveal reveal-delay-2">
              The companies winning right now aren't the biggest — they're the ones moving fastest. Sarmadi gives small and midsize businesses the AI capability that, until now, only the largest could afford to build.
            </p>
            <div className="hero-gen-cta reveal reveal-delay-3">
              <a href="contact.html" className="btn btn-gradient">Start a project <span className="arrow">→</span></a>
              <a href="services.html" className="btn btn-ghost btn-ghost-dark">See what we build</a>
            </div>
          </div>
          <div className="hero-gen-right reveal reveal-delay-2">
            <ThinkingTerminal />
            <div className="hero-gen-meta">
              <div>
                <div className="eyebrow" style={{ color: "rgba(255,255,255,0.5)" }}>Built for</div>
                <div className="hero-gen-meta-val">SMB & Mid-market</div>
              </div>
              <div>
                <div className="eyebrow" style={{ color: "rgba(255,255,255,0.5)" }}>Based in</div>
                <div className="hero-gen-meta-val">Houston, Texas</div>
              </div>
              <div>
                <div className="eyebrow" style={{ color: "rgba(255,255,255,0.5)" }}>Working since</div>
                <div className="hero-gen-meta-val">2024</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function ServicesGenerative() {
  return (
    <section className="section services-gen">
      <div className="container">
        <div className="services-gen-head">
          <div className="eyebrow eyebrow-dot">What we build</div>
          <h2 className="display" style={{ fontSize: "clamp(40px, 6vw, 96px)", margin: "20px 0 0", lineHeight: 0.96, maxWidth: 1100 }}>
            Six capabilities. <em className="display-italic gradient-text">One studio.</em>
          </h2>
        </div>
        <div className="services-gen-grid">
          {SERVICES_DATA.map((s, i) => (
            <article key={s.n} className="service-gen-card" style={{ "--delay": `${i * 0.06}s` }}>
              <div className="service-gen-num display gradient-text">{s.n}</div>
              <h3 className="display" style={{ fontSize: 32, margin: "20px 0 12px" }}>{s.title}</h3>
              <p className="service-gen-body">{s.body}</p>
              <div className="service-gen-keywords">
                {s.keywords.map(k => <span key={k}>{k}</span>)}
              </div>
              <div className="service-gen-glow"></div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function ProofGenerative() {
  const items = [
    { label: "Contract review time", before: 100, after: 8, unit: "%", note: "Legal · doc-intake agent" },
    { label: "Listing copy turnaround", before: 100, after: 12, unit: "%", note: "Real estate · drafting agent" },
    { label: "Patient intake handoffs", before: 100, after: 24, unit: "%", note: "Healthcare · triage RAG" },
    { label: "Vendor onboarding cycle", before: 100, after: 35, unit: "%", note: "Operations · workflow agent" },
  ];
  const [animate, setAnimate] = useStateH(false);
  const ref = useRefH(null);

  useEffectH(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(
      ([e]) => { if (e.isIntersecting) { setAnimate(true); obs.disconnect(); } },
      { threshold: 0.25 }
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);

  return (
    <section className="section proof-gen" ref={ref}>
      <div className="container">
        <div className="proof-gen-head">
          <div className="eyebrow eyebrow-dot">Outcomes</div>
          <h2 className="display" style={{ fontSize: "clamp(40px, 6vw, 88px)", margin: "20px 0 0", lineHeight: 0.96, maxWidth: 1100 }}>
            What it looks like<br/>when it <em className="display-italic gradient-text">works.</em>
          </h2>
        </div>
        <div className="proof-gen-grid">
          {items.map((it, i) => (
            <div key={i} className="proof-gen-row">
              <div className="proof-gen-left">
                <div className="proof-gen-label">{it.label}</div>
                <div className="proof-gen-note muted">{it.note}</div>
              </div>
              <div className="proof-gen-bars">
                <div className="proof-gen-bar-row">
                  <span className="proof-gen-bar-tag">before</span>
                  <div className="proof-gen-bar-track">
                    <div className="proof-gen-bar proof-gen-bar-before" style={{ width: animate ? `${it.before}%` : "0%", transitionDelay: `${i * 0.12}s` }}></div>
                  </div>
                  <span className="proof-gen-bar-val">100</span>
                </div>
                <div className="proof-gen-bar-row">
                  <span className="proof-gen-bar-tag" style={{ color: "#fff" }}>after</span>
                  <div className="proof-gen-bar-track">
                    <div className="proof-gen-bar proof-gen-bar-after" style={{ width: animate ? `${it.after}%` : "0%", transitionDelay: `${i * 0.12 + 0.4}s` }}></div>
                  </div>
                  <span className="proof-gen-bar-val gradient-text">{it.after}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function ProcessGenerative() {
  return (
    <section className="section process-gen">
      <div className="container">
        <div className="eyebrow eyebrow-dot" style={{ color: "rgba(255,255,255,0.6)" }}>How we work</div>
        <h2 className="display" style={{ fontSize: "clamp(40px, 6vw, 96px)", margin: "20px 0 80px", lineHeight: 0.96, color: "#fff" }}>
          A working product in weeks.<br/>
          <em className="display-italic gradient-text">Not a roadmap in months.</em>
        </h2>
        <div className="process-gen-rail">
          {PROCESS_DATA.map((p, i) => (
            <div key={p.phase} className="process-gen-node">
              <div className="process-gen-marker">
                <span className="process-gen-marker-glow"></span>
                <span className="process-gen-marker-dot"></span>
              </div>
              <div className="process-gen-phase eyebrow gradient-text">Phase {p.phase}</div>
              <h3 className="display" style={{ fontSize: 32, margin: "8px 0 12px", color: "#fff" }}>{p.label}</h3>
              <p className="process-gen-body">{p.body}</p>
            </div>
          ))}
          <div className="process-gen-line"></div>
        </div>
      </div>
    </section>
  );
}

function CtaGenerative() {
  return (
    <section className="section cta-gen">
      <div className="cta-gen-bg">
        <FlowFieldCanvas />
        <div className="cta-gen-vignette"></div>
      </div>
      <div className="container center cta-gen-inner">
        <h2 className="display" style={{ fontSize: "clamp(56px, 11vw, 196px)", margin: 0, lineHeight: 0.88, color: "#fff" }}>
          Move<br/>
          <em className="display-italic gradient-text">first.</em>
        </h2>
        <p style={{ fontSize: 18, marginTop: 32, maxWidth: 600, marginLeft: "auto", marginRight: "auto", color: "rgba(255,255,255,0.7)", lineHeight: 1.5 }}>
          A 30-minute call about your business and where AI fits. No deck, no pitch — just a clear answer.
        </p>
        <div style={{ marginTop: 48, display: "flex", gap: 16, justifyContent: "center", flexWrap: "wrap" }}>
          <a href="contact.html" className="btn btn-gradient">Book a call <span className="arrow">→</span></a>
          <a href="work.html" className="btn btn-ghost btn-ghost-dark">See the work</a>
        </div>
      </div>
    </section>
  );
}

function Home() {
  useRevealOnScroll();

  return (
    <div>
      <Nav active="home" />
      <HeroGenerative />
      <ServicesGenerative />
      <ProofGenerative />
      <ProcessGenerative />
      <CtaGenerative />
      <Footer />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<Home />);
