// sections.jsx — Sinatra Labs site sections

const { useEffect: _useEffect, useRef: _useRef, useState: _useState } = React;

/* ---------- Process ---------- */
const PROCESS_STAGES = [
  {
    n: "01",
    name: "Discovery",
    weeks: "Scope",
    blurb: "We sit with the team that owns the problem. Read the playbook. Watch the failure modes. Leave with a one-page brief and a number we'll be measured against.",
    items: [
      "Problem framing",
      "Success metric & eval set",
      "Data & systems audit",
      "Risk register",
      "Build vs. buy call",
    ],
  },
  {
    n: "02",
    name: "Design",
    weeks: "System design",
    blurb: "We design the system before we write it. Surfaces, agent boundaries, evals, fallbacks. The document that comes out becomes the plan we work from — and the one we'll keep refining as the work gets sharper.",
    items: [
      "Surface & agent map",
      "Eval harness",
      "Tool & API contracts",
      "Latency & cost budget",
      "Rollback plan",
    ],
  },
  {
    n: "03",
    name: "Build",
    weeks: "Implementation",
    blurb: "Senior engineers, in your repo, on your standup. Pairs of two. Daily PRs. Evals run on every commit. Nothing is delivered as a slide; everything is delivered as a merge.",
    items: [
      "Agent loop & tools",
      "Eval-driven development",
      "Observability & traces",
      "Guardrails & policies",
      "Code review with your team",
    ],
  },
  {
    n: "04",
    name: "Activate",
    weeks: "Activation",
    blurb: "We don't celebrate the demo. We focus on adoption. Canaries first, then a percentage, then everyone. Your on-call rotation, your dashboards, your runbook — handed off, not hovered over.",
    items: [
      "Gradual rollout",
      "Production runbook",
      "On-call handoff",
      "Eval thresholds in CI",
      "Live tuning",
    ],
  },
  {
    n: "05",
    name: "Compound",
    weeks: "Optimization",
    blurb: "Most of the value shows up in live use, not the first reveal. We stay on a retainer or step back entirely — your call. Either way, the system is yours, the code is yours, the evals are yours.",
    items: [
      "Regular model upgrades",
      "Eval drift monitoring",
      "Second-system planning",
      "Team enablement",
      "Optional retainer",
    ],
  },
];

function Process() {
  const containerRef = _useRef(null);
  const graphRef = _useRef(null);
  const pathRef = _useRef(null);
  const dotRef = _useRef(null);
  const [progress, setProgress] = _useState(0);
  const [pathLength, setPathLength] = _useState(0);
  const [curvePoint, setCurvePoint] = _useState({ x: 0, y: 160 });

  _useEffect(() => {
    const onScroll = () => {
      const vh = window.innerHeight;

      const graphEl = graphRef.current;
      if (graphEl) {
        const graphRect = graphEl.getBoundingClientRect();
        if (graphRect.height > 24) {
          const start = vh * 0.9;
          const end = vh * 0.18;
          const p = Math.max(0, Math.min(1, (start - graphRect.top) / (start - end)));
          setProgress(p);
          return;
        }
      }

      const el = containerRef.current;
      if (!el) return;
      const r = el.getBoundingClientRect();
      const total = r.height + vh * 0.35;
      const seen = vh * 0.9 - r.top;
      const p = Math.max(0, Math.min(1, seen / total));
      setProgress(p);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);

  _useEffect(() => {
    const path = pathRef.current;
    if (!path || !path.getTotalLength) return;
    const measure = () => setPathLength(path.getTotalLength());
    measure();
    window.addEventListener("resize", measure);
    return () => { window.removeEventListener("resize", measure); };
  }, []);

  _useEffect(() => {
    const path = pathRef.current;
    if (!path || !path.getTotalLength || !pathLength) return;
    const pt = path.getPointAtLength(pathLength * progress);
    setCurvePoint({ x: pt.x, y: pt.y });
  }, [progress, pathLength]);

  const path =
    "M 0 160 " +
    "C 60 158, 90 152, 120 140 " +
    "S 240 110, 300 105 " +
    "S 440 95, 500 88 " +
    "S 640 78, 700 70 " +
    "S 840 50, 900 36 " +
    "S 980 20, 1000 14";

  return (
    <section id="process" className="process paper" ref={containerRef}>
      <div className="container">
        <div className="section-head">
          <h2>
            Five stages. <em>One growth curve.</em>
          </h2>
        </div>

        <div className="process-curve" aria-hidden="true">
          <div className="process-axis">
            {PROCESS_STAGES.map((s) => (
              <div className="process-axis-cell" key={s.n}>
                <span className="process-axis-num">{s.n}</span>
                <span className="process-axis-name">{s.name}</span>
                <span className="process-axis-weeks">{s.weeks}</span>
              </div>
            ))}
          </div>

          <div className="process-graph" ref={graphRef}>
            <span className="process-y-axis">growth &rarr;</span>
            <svg viewBox="0 0 1000 200" className="process-svg" preserveAspectRatio="none">
              <defs>
                <linearGradient id="curveGradient" x1="0" x2="1" y1="0" y2="0">
                  <stop offset="0%"   stopColor="oklch(0.55 0.05 var(--neon-hue))" stopOpacity="0.5" />
                  <stop offset="50%"  stopColor="oklch(0.7 0.22 var(--neon-hue))"  stopOpacity="0.95" />
                  <stop offset="100%" stopColor="oklch(0.78 0.27 var(--neon-hue))" stopOpacity="1" />
                </linearGradient>
                <filter id="curveGlow">
                  <feGaussianBlur stdDeviation="2.4" result="b" />
                  <feMerge>
                    <feMergeNode in="b" />
                    <feMergeNode in="SourceGraphic" />
                  </feMerge>
                </filter>
              </defs>
              {[100, 300, 500, 700, 900].map((x, i) => (
                <line key={i} x1={x} y1={0} x2={x} y2={200} className="process-divider" />
              ))}
              <line x1="0" y1="180" x2="1000" y2="180" className="process-baseline" />
              <path d={path} className="process-curve-bg" />
              <path
                ref={pathRef}
                d={path}
                className="process-curve-fg"
                style={{
                  strokeDasharray: pathLength || 0,
                  strokeDashoffset: (pathLength || 0) * (1 - progress),
                }}
                filter="url(#curveGlow)"
              />
              <circle ref={dotRef} r="9" className="process-end" cx={curvePoint.x} cy={curvePoint.y} filter="url(#curveGlow)" />
              <circle r="3" className="process-end-core" cx={curvePoint.x} cy={curvePoint.y} />
            </svg>
          </div>

          <div className="process-rows">
            {PROCESS_STAGES.map((s, i) => (
              <Reveal key={s.n} delay={i * 80} className="process-col">
                <p className="process-blurb">{s.blurb}</p>
                <ul className="process-items">
                  {s.items.map((it) => (
                    <li key={it}><span className="process-arrow">&rarr;</span> {it}</li>
                  ))}
                </ul>
              </Reveal>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Team ---------- */
function Team() {
  const onTeamPage = typeof isTeamPagePath === "function" && isTeamPagePath();
  const HeadingTag = onTeamPage ? "h1" : "h2";

  if (onTeamPage) {
    return (
      <section id="team" className="team paper">
        <div className="container">
          <div className="team-brief">
            <HeadingTag className="sr-only">Team</HeadingTag>
            <Reveal className="team-brief-copy">
              <p>
                Sinatra Labs is founder-led. Every engagement is run by Nick directly, the same
                person who will scope the work, design the system, and work with your solution.
                Nick brings a manufacturing mindset, systems engineering background, and
                Anthropic certifications to secure, enterprise-ready AI delivery.
              </p>
            </Reveal>
            <Reveal delay={120} className="team-brief-cta">
              <a href="https://calendly.com/nick-sinatralabs/30min" target="_blank" rel="noopener" className="btn btn-lg">
                <span>Schedule a Working Session</span>
                <span className="arrow">&rarr;</span>
              </a>
            </Reveal>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section id="team" className="team paper">
      <div className="container">
        <HeadingTag className="sr-only">Team</HeadingTag>

        <div className="team-mag">

          {/* Column A — Portrait */}
          <div className="team-mag-a">
            <Reveal>
              <div className="team-portrait" aria-label={`Portrait — ${member.name}`}>
                <div className="team-portrait-stripes" />
                <span className="team-portrait-cap">PORTRAIT</span>
              </div>
            </Reveal>
          </div>

          {/* Column B — Identity, pull quote, credentials */}
          <div className="team-mag-b">
            <Reveal className="team-mag-identity">
              <div className="team-name">{member.name}</div>
              <div className="team-role eyebrow">{member.role}</div>
            </Reveal>

            <Reveal delay={240} className="team-mag-stats">
              {[
                { n: "SD",     label: "San Diego, CA" },
              ].map((s) => (
                <div key={s.label} className="team-stat">
                  <span className="team-stat-n">{s.n}</span>
                  <span className="team-stat-label">{s.label}</span>
                </div>
              ))}
            </Reveal>
          </div>

          {/* Column C — Bio */}
          <div className="team-mag-c">
            <Reveal>
              <p className="team-mag-lede">From production floors to production systems.</p>
            </Reveal>
            <Reveal delay={80}>
              <p>
                A background in enterprise technology, Systems Engineering, Operations and
                Delivery. I understand the systems that run businesses not just the models
                that can transform them.
              </p>
            </Reveal>
            <Reveal delay={240}>
              <p className="team-coda">No subcontractors. No junior handoffs. No decks.</p>
            </Reveal>
          </div>

        </div>
      </div>
    </section>
  );
}

function TeamPageCTA() {
  return (
    <section id="contact" className="team-page-cta paper">
      <div className="container">
        <Reveal className="team-page-cta-inner">
          <a href="https://calendly.com/nick-sinatralabs/30min" target="_blank" rel="noopener" className="btn btn-lg">
            <span>Schedule a Working Session</span>
            <span className="arrow">&rarr;</span>
          </a>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- Contact ---------- */
function Contact() {
  const [form, setForm] = _useState({ name: "", email: "", company: "", message: "" });
  const [sent, setSent] = _useState(false);

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!form.name || !form.email) return;
    setSent(true);
    const bookingUrl = new URL("https://calendly.com/nick-sinatralabs/30min");
    bookingUrl.searchParams.set("name", form.name);
    bookingUrl.searchParams.set("email", form.email);
    const notes = [form.company && `Company: ${form.company}`, form.message].filter(Boolean).join("\n\n");
    if (notes) bookingUrl.searchParams.set("a1", notes);
    if (window.openBooking) {
      window.openBooking({ url: bookingUrl.toString() });
    } else {
      window.open(bookingUrl.toString(), "_blank", "noopener");
    }
  };

  return (
    <section id="contact" className="contact paper">
      <div className="container">
        <div className="section-head">
          <h2>
            <SplitLines stagger={90}>{"Let's Build Something."}</SplitLines>
          </h2>
        </div>

        <div className="contact-layout">
          <Reveal className="contact-lede">
            <p className="contact-body">
              We keep our client list intentionally small. If you have a workflow you're
              certain AI could run but no team to bring it to life, tell us about it below.
              Twenty minutes. You'll talk to a founder.
            </p>
            <a href="mailto:Nick@sinatralabs.com" className="contact-email">Nick@sinatralabs.com</a>
          </Reveal>

          <Reveal delay={150} className="contact-form-wrap">
            {sent ? (
              <div className="contact-thanks">
                <div className="contact-thanks-icon">&#10003;</div>
                <p>Got it, {form.name.split(" ")[0]}. Pick a time that works for you.</p>
              </div>
            ) : (
              <form className="contact-form" onSubmit={handleSubmit} noValidate>
                <div className="cf-row">
                  <div className="cf-field">
                    <label className="cf-label eyebrow" htmlFor="cf-name">Name</label>
                    <input
                      id="cf-name"
                      className="cf-input"
                      type="text"
                      placeholder="Frank Sinatra"
                      value={form.name}
                      onChange={set("name")}
                      required
                    />
                  </div>
                  <div className="cf-field">
                    <label className="cf-label eyebrow" htmlFor="cf-email">Email</label>
                    <input
                      id="cf-email"
                      className="cf-input"
                      type="email"
                      placeholder="frank@yourco.com"
                      value={form.email}
                      onChange={set("email")}
                      required
                    />
                  </div>
                </div>

                <div className="cf-field">
                  <label className="cf-label eyebrow" htmlFor="cf-company">Company</label>
                  <input
                    id="cf-company"
                    className="cf-input"
                    type="text"
                    placeholder="Your company or project"
                    value={form.company}
                    onChange={set("company")}
                  />
                </div>

                <div className="cf-field">
                  <label className="cf-label eyebrow" htmlFor="cf-message">What are you working on?</label>
                  <textarea
                    id="cf-message"
                    className="cf-input cf-textarea"
                    placeholder="Describe the workflow, the bottleneck, or the idea. One paragraph is enough."
                    rows={4}
                    value={form.message}
                    onChange={set("message")}
                  />
                </div>

                <button type="submit" className="cf-submit">
                  <span>Schedule a Working Session</span>
                  <span className="arrow">&rarr;</span>
                </button>
              </form>
            )}
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  const onTeamPage = typeof isTeamPagePath === "function" && isTeamPagePath();
  const processHref = onTeamPage ? "index.html#process" : "#process";
  const teamHref    = onTeamPage ? "#team" : "team.html#team";
  const contactHref = "#contact";

  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="wordmark footer-mark">
              <span className="sinatra sinatra-script">Sinatra</span>
            </div>
            <p className="footer-tag"><em>The agentic engineering firm.</em></p>
          </div>
          <div>
            <div className="eyebrow">Sitemap</div>
            <ul className="footer-list">
              <li><a href={processHref}>Process</a></li>
              <li><a href={teamHref}>Team</a></li>
              <li><a href={contactHref}>Contact</a></li>
            </ul>
          </div>
          <div>
            <div className="eyebrow">Credentials</div>
            <ul className="footer-list">
              <li>Anthropic Services Partner</li>
              <li>SOC 2 Type II</li>
              <li>San Diego, California</li>
            </ul>
          </div>
          <div>
            <div className="eyebrow">Get in touch</div>
            <ul className="footer-list">
              <li><a href="mailto:Nick@sinatralabs.com">Nick@sinatralabs.com</a></li>
              <li><a href="https://calendly.com/nick-sinatralabs/30min" target="_blank" rel="noopener">Schedule a Working Session &#8599;</a></li>
            </ul>
          </div>
        </div>

        <div className="footer-signoff">
          <span className="footer-signoff-text"><em>Production grade solutions</em></span>
        </div>

        <div className="footer-meta">
          <span>&copy; 2026 Sinatra Labs, Inc.</span>
          <span>Privacy &middot; Terms</span>
          <span>San Diego</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Process, Team, TeamPageCTA, Contact, Footer });
