/* global React, ReactDOM */

const { useState, useEffect } = React;

// ----- Supabase -----
// This is a static site (React via CDN, no build step), so the publishable
// key is embedded client-side. That is by design: publishable keys are safe
// to expose — Row Level Security on the `contact_submissions` table is the
// real security boundary (anon may INSERT only, never SELECT). See
// supabase.sql for the table + policy this expects.
const SUPABASE_URL = "https://ngcawgewyfcyckpnybsw.supabase.co";
const SUPABASE_PUBLISHABLE_KEY = "sb_publishable_lx4ObdbrqBM__hnWEuaqdQ_v7HktLCi";
const SUPABASE_TABLE = "contact_submissions";

async function submitBrief(form) {
  const res = await fetch(
    `${SUPABASE_URL}/rest/v1/${SUPABASE_TABLE}`,
    {
      method: "POST",
      headers: {
        apikey: SUPABASE_PUBLISHABLE_KEY,
        Authorization: `Bearer ${SUPABASE_PUBLISHABLE_KEY}`,
        "Content-Type": "application/json",
        Prefer: "return=minimal",
      },
      body: JSON.stringify({
        name: form.name.trim(),
        email: form.email.trim(),
        org: form.org.trim() || null,
        role: form.role.trim() || null,
        interests: form.interests,
        timeline: form.timeline,
        budget: form.budget,
        artifact: form.artifact.trim() || null,
        expert: form.expert.trim() || null,
        about: form.about.trim(),
        referral: form.referral.trim() || null,
      }),
    }
  );
  if (!res.ok) {
    const detail = await res.text().catch(() => "");
    throw new Error(`Supabase ${res.status}: ${detail || res.statusText}`);
  }
}

// ----- shared bits (lightweight copies) -----
function Logo() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="12" r="10.5" stroke="currentColor" strokeWidth="1.5" />
      <path d="M12 1.5 V 22.5" stroke="currentColor" strokeWidth="1.5" />
      <rect x="12.5" y="2" width="9.5" height="20" fill="currentColor" />
    </svg>
  );
}
function Arrow({ size = 14 }) {
  return (
    <svg className="arrow" width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}
function Nav() {
  return (
    <nav className="nav">
      <div className="shell nav-inner">
        <a href="index.html" className="logo">
          <Logo />
          <span>Half&nbsp;Machine</span>
        </a>
        <div className="nav-links" style={{ display: window.innerWidth > 720 ? "flex" : "none" }}>
          <a href="index.html#thesis">Thesis</a>
          <a href="index.html#capabilities">Capabilities</a>
          <a href="index.html#offers">Offers</a>
          <a href="index.html#work">Work</a>
        </div>
        <a href="#form" className="nav-cta" style={{ background: "transparent", color: "var(--ink)" }}>
          Get in touch
          <Arrow />
        </a>
      </div>
    </nav>
  );
}
function Foot() {
  return (
    <footer className="foot">
      <div className="shell foot-inner">
        <div>© Half Machine 2026 · Half human · Half machine</div>
        <div>v1.0 · Sydney AUS</div>
      </div>
    </footer>
  );
}

// ----- contact form -----
const INTERESTS = [
  "Agent Design Sprint",
  "Vertical Agent Prototype",
  "AI Venture Build Partner",
  "Fast Website Build",
  "Setup autonomous agent",
  "Something else",
];

const TIMELINES = [
  { v: "now",     l: "Now" },
  { v: "1-3m",    l: "1–3 mo" },
  { v: "3-6m",    l: "3–6 mo" },
  { v: "exploring", l: "Exploring" },
];

const BUDGETS = [
  { v: "<25k",  l: "< $25k" },
  { v: "25-75", l: "$25–75k" },
  { v: "75-200",l: "$75–200k" },
  { v: ">200k", l: "$200k +" },
  { v: "tbd",   l: "TBD" },
];

function CheckMark() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
      <path d="M5 12.5l4.5 4.5L19 7.5" stroke="var(--accent)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function ContactForm() {
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [form, setForm] = useState({
    name: "",
    email: "",
    org: "",
    role: "",
    interests: [],
    timeline: "1-3m",
    budget: "tbd",
    artifact: "",
    expert: "",
    about: "",
    referral: "",
  });

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const toggle = (k, v) => setForm((f) => ({
    ...f,
    [k]: f[k].includes(v) ? f[k].filter((x) => x !== v) : [...f[k], v],
  }));

  const canSubmit = form.name.trim() && form.email.trim() && form.about.trim();

  async function submit(e) {
    e.preventDefault();
    if (!canSubmit || submitting) return;
    setSubmitting(true);
    setError("");
    try {
      await submitBrief(form);
      setSubmitted(true);
      setTimeout(() => {
        window.scrollTo({ top: document.getElementById("form").offsetTop - 80, behavior: "smooth" });
      }, 50);
    } catch (err) {
      setError(
        "Something went wrong sending your brief. Please try again in a moment."
      );
      console.error(err);
    } finally {
      setSubmitting(false);
    }
  }

  if (submitted) {
    return (
      <div className="contact-form-card" id="form">
        <div className="form-head">
          <span className="title">Half Machine · Brief</span>
          <span className="step">Received</span>
        </div>
        <div className="success">
          <div className="glyph"><CheckMark /></div>
          <h3>Thanks, <em>{form.name.split(" ")[0] || "friend"}</em>. We'll be in touch within one working&nbsp;day.</h3>
          <p>
            A short note is heading to your inbox at <strong>{form.email}</strong> with next steps. If your brief is a fit for a sprint, we'll send a calendar link to set up a 30-minute call.
          </p>
          <div className="summary">
            <div className="row">
              <div className="k">Sent at</div>
              <div className="v">{new Date().toLocaleString()}</div>
            </div>
            {form.org && (
              <div className="row">
                <div className="k">Organisation</div>
                <div className="v">{form.org}</div>
              </div>
            )}
            {form.interests.length > 0 && (
              <div className="row">
                <div className="k">Interested in</div>
                <div className="v">{form.interests.join(" · ")}</div>
              </div>
            )}
            <div className="row">
              <div className="k">Timeline</div>
              <div className="v">{TIMELINES.find((t) => t.v === form.timeline)?.l}</div>
            </div>
            <div className="row">
              <div className="k">Budget</div>
              <div className="v">{BUDGETS.find((b) => b.v === form.budget)?.l}</div>
            </div>
          </div>
          <div style={{ marginTop: 28, display: "flex", gap: 12, flexWrap: "wrap" }}>
            <a className="btn btn-ghost" href="index.html">Back to home</a>
            <button className="btn btn-ghost" onClick={() => { setSubmitted(false); setError(""); }}>
              Send another
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <form className="contact-form-card" id="form" onSubmit={submit}>
      <div className="form-head">
        <span className="title">Half Machine · Brief</span>
        <span className="step">{`< 2 min`}</span>
      </div>

      <div className="field-row">
        <div className="field">
          <label>Name</label>
          <input
            className="input"
            type="text"
            required
            placeholder="Jane Doe"
            value={form.name}
            onChange={(e) => set("name", e.target.value)}
          />
        </div>
        <div className="field">
          <label>Email</label>
          <input
            className="input"
            type="email"
            required
            placeholder="jane@company.com"
            value={form.email}
            onChange={(e) => set("email", e.target.value)}
          />
        </div>
      </div>

      <div className="field-row">
        <div className="field">
          <label>Organisation <span className="opt">— optional</span></label>
          <input
            className="input"
            type="text"
            placeholder="Company or venture"
            value={form.org}
            onChange={(e) => set("org", e.target.value)}
          />
        </div>
        <div className="field">
          <label>Your role <span className="opt">— optional</span></label>
          <input
            className="input"
            type="text"
            placeholder="Founder · Operator · Lead"
            value={form.role}
            onChange={(e) => set("role", e.target.value)}
          />
        </div>
      </div>

      <div className="field">
        <div className="lbl">
          <span>What are you interested in?</span>
          <span className="opt">— pick any</span>
        </div>
        <div className="chip-grid">
          {INTERESTS.map((i) => (
            <button
              type="button"
              key={i}
              className={"chip" + (form.interests.includes(i) ? " active" : "")}
              onClick={() => toggle("interests", i)}
            >
              <span className="check" />
              {i}
            </button>
          ))}
        </div>
      </div>

      <div className="field-row">
        <div className="field">
          <div className="lbl"><span>Timeline</span></div>
          <div className="segmented">
            {TIMELINES.map((t) => (
              <button
                type="button"
                key={t.v}
                className={"seg" + (form.timeline === t.v ? " active" : "")}
                onClick={() => set("timeline", t.v)}
              >{t.l}</button>
            ))}
          </div>
        </div>
        <div className="field">
          <div className="lbl"><span>Budget</span></div>
          <div className="segmented" style={{ gridTemplateColumns: "repeat(5, 1fr)" }}>
            {BUDGETS.map((b) => (
              <button
                type="button"
                key={b.v}
                className={"seg" + (form.budget === b.v ? " active" : "")}
                onClick={() => set("budget", b.v)}
              >{b.l}</button>
            ))}
          </div>
        </div>
      </div>

      <div className="field-row">
        <div className="field">
          <label>What artifact does the agent produce? <span className="opt">— if known</span></label>
          <input
            className="input"
            type="text"
            placeholder="Estimate · Diagnosis · Report · Plan"
            value={form.artifact}
            onChange={(e) => set("artifact", e.target.value)}
          />
        </div>
        <div className="field">
          <label>Who's the expert? <span className="opt">— if known</span></label>
          <input
            className="input"
            type="text"
            placeholder="QS · Clinician · Analyst · Lawyer"
            value={form.expert}
            onChange={(e) => set("expert", e.target.value)}
          />
        </div>
      </div>

      <div className="field">
        <label>Tell us what you're trying to build</label>
        <textarea
          className="textarea"
          required
          rows={5}
          placeholder="The shape of the workflow, the decision, or the product you have in mind. A paragraph is fine."
          value={form.about}
          onChange={(e) => set("about", e.target.value)}
        />
      </div>

      <div className="field">
        <label>How did you find us? <span className="opt">— optional</span></label>
        <input
          className="input"
          type="text"
          placeholder="Word of mouth, an essay, a friend…"
          value={form.referral}
          onChange={(e) => set("referral", e.target.value)}
        />
      </div>

      <div className="form-foot">
        <div className="note">
          {error ? (
            <span style={{ color: "var(--accent)" }}>{error}</span>
          ) : (
            "We read every brief. If it's a fit, you'll hear from a real human within one working day."
          )}
        </div>
        <button className="btn-submit" type="submit" disabled={!canSubmit || submitting}>
          {submitting ? "Sending…" : "Send brief"}
          <Arrow />
        </button>
      </div>
    </form>
  );
}

// ----- aside -----
function Aside() {
  return (
    <aside className="contact-aside">
      <span className="eyebrow"><span className="dot" />Get in touch</span>
      <h1>Tell us what you're trying to <em>build</em>.</h1>
      <p className="lede">
        Briefs work best when they start from the artifact, the expert, and the workflow. The form on the right is shaped around that — but a paragraph is more than enough.
      </p>

      <div className="status-pill">
        <span className="pulse" />
        Taking on 2 sprints · Q3 2026
      </div>

      <div className="channels">
        <div className="channel">
          <div className="k">Calls</div>
          <div className="v">
            <a href="#form">Book a 30-min intro →</a>
            <span className="sub">If your brief is a fit, we'll send a link.</span>
          </div>
        </div>
        <div className="channel">
          <div className="k">Response</div>
          <div className="v">
            Within 1 working day
            <span className="sub">Mon–Fri · AEST</span>
          </div>
        </div>
        <div className="channel">
          <div className="k">Based</div>
          <div className="v">
            Sydney, Australia
            <span className="sub">Remote with ventures worldwide.</span>
          </div>
        </div>
        <div className="channel" style={{ borderBottom: "none" }}>
          <div className="k">Elsewhere</div>
          <div className="v">
            <a href="#" style={{ marginRight: 16 }}>X / Twitter ↗</a>
            <a href="#" style={{ marginRight: 16 }}>LinkedIn ↗</a>
            <a href="#">Substack ↗</a>
          </div>
        </div>
      </div>
    </aside>
  );
}

// ----- faq -----
const FAQ = [
  { q: "Do you work with pre-product founders?",
    a: "Often. The earlier you come in, the more useful we are — we help shape the strongest agent opportunity from the underlying workflow, then design backwards into product." },
  { q: "What does a typical engagement look like?",
    a: "Most start with a 2-week Agent Design Sprint, which produces a designed concept and an opinion on whether to prototype. From there we either build, hand off, or wind down — clean either way." },
  { q: "Will you sign an NDA?",
    a: "Yes. We're happy to sign mutual NDAs before sharing anything sensitive. Send yours, or use ours." },
  { q: "What about equity, retainers, or fixed fee?",
    a: "All three, depending on stage and scope. Sprints are fixed-fee, prototypes are scoped, longer venture work mixes cash and equity." },
];

function FAQItem({ q, a }) {
  return (
    <div className="faq-item">
      <div className="faq-q" dangerouslySetInnerHTML={{ __html: q.replace(/\*([^*]+)\*/g, "<em>$1</em>") }} />
      <div className="faq-a">{a}</div>
    </div>
  );
}

function FAQSection() {
  return (
    <section className="faq-section">
      <div className="shell">
        <div className="section-head">
          <span className="eyebrow"><span className="dot" />FAQ</span>
          <div>
            <h2>Common <em>questions</em>, briefly.</h2>
            <p>If yours isn't here, ask in the brief — we'll answer in our reply.</p>
          </div>
        </div>
        <div className="faq-list">
          {FAQ.map((item) => <FAQItem key={item.q} {...item} />)}
        </div>
      </div>
    </section>
  );
}

// ----- tweaks (smaller, accent only) -----
function Tweaks() {
  const TweaksPanel = window.TweaksPanel;
  const useTweaks   = window.useTweaks;
  const TweakSection = window.TweakSection;
  const TweakColor   = window.TweakColor;
  if (!TweaksPanel || !useTweaks) return null;

  const [t, setTweak] = useTweaks(/*EDITMODE-BEGIN*/{
    "accent": "oklch(0.62 0.14 50)"
  }/*EDITMODE-END*/);

  useEffect(() => {
    document.documentElement.style.setProperty("--accent", t.accent);
    document.documentElement.style.setProperty(
      "--accent-soft",
      t.accent.replace(/^oklch\(([^)]+)\)$/, "oklch($1 / 0.12)")
    );
  }, [t.accent]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Accent">
        <TweakColor
          label="Color"
          value={t.accent}
          onChange={(v) => setTweak("accent", v)}
          options={[
            "oklch(0.62 0.14 50)",
            "oklch(0.55 0.13 250)",
            "oklch(0.58 0.14 145)",
            "oklch(0.62 0.16 12)",
          ]}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

// ----- app -----
function App() {
  return (
    <>
      <Nav />
      <section className="contact-page">
        <div className="shell">
          <div className="contact-grid-page">
            <Aside />
            <ContactForm />
          </div>
        </div>
      </section>
      <FAQSection />
      <Foot />
      <Tweaks />
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
