/* AgentMart pre-launch landing — interactive React app */

const { useState, useEffect, useMemo, useRef } = React;

// ── Icons (1.3 stroke, no fills, minimal) ─────────────────────────────────
const Ico = {
  arrow: () => <span className="arr" aria-hidden="true">→</span>,
  check: (props) => (
    <svg viewBox="0 0 16 16" {...props}><path d="M3 8.2 6.5 11.5 13 5" /></svg>
  ),
  curate: () => (
    <svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h10M4 18h16" strokeLinecap="round"/></svg>
  ),
  spec: () => (
    <svg viewBox="0 0 24 24"><rect x="4" y="3" width="16" height="18" rx="2"/><path d="M8 8h8M8 12h8M8 16h5"/></svg>
  ),
  pay: () => (
    <svg viewBox="0 0 24 24"><rect x="3" y="6" width="18" height="12" rx="2"/><path d="M3 10h18M7 15h3"/></svg>
  ),
  hand: () => (
    <svg viewBox="0 0 24 24"><path d="M6 12V7a2 2 0 1 1 4 0v5"/><path d="M10 11V5a2 2 0 1 1 4 0v7"/><path d="M14 11V7a2 2 0 1 1 4 0v8a5 5 0 0 1-5 5h-3a4 4 0 0 1-4-4l-2-4a1.5 1.5 0 0 1 2.4-1.8L6 12"/></svg>
  ),
  market: () => (
    <svg viewBox="0 0 24 24"><path d="M3 7h18l-1.5 4H4.5L3 7zM5 11v9h14v-9M9 20v-5h6v5"/></svg>
  ),
};

// ── Top nav ────────────────────────────────────────────────────────────────
function Nav({ onCta }) {
  return (
    <header className="nav">
      <div className="wrap nav-row">
        <a className="brand" href="#">
          <span className="brand-mark" aria-hidden="true">
            <img src="agentmart_favicon.svg" alt="" />
          </span>
          <span className="brand-name">Agent<em>Mart</em></span>
        </a>
        <nav className="nav-links">
          <a href="#problem">The problem</a>
          <a href="#solution">How it works</a>
          <a href="#buyers">Buyers</a>
          <a href="#sellers">Sellers</a>
        </nav>
        <div className="nav-right">
          <button className="btn btn-primary btn-sm" onClick={() => onCta('buyer')}>
            Get early access <Ico.arrow />
          </button>
        </div>
      </div>
    </header>
  );
}

// ── Hero ───────────────────────────────────────────────────────────────────
function Hero({ onCta, brand1, brand2 }) {
  return (
    <section className="hero" data-screen-label="01 Hero">
      <div className="hero-shader">
        <ShaderAnimation colorA={brand1} colorB={brand2} colorBg="#07060d" intensity={0.95} />
      </div>
      <div className="hero-vignette" />
      <div className="wrap">
        <div className="hero-inner">
          <div className="hero-eyebrow">
            <span className="eyebrow"><span className="dot"/> Early access · Fall 2026</span>
            <span className="seat-count">Cohort 01 · 400 seats</span>
          </div>
          <h1>
            AI agents<br/>
            that <em>actually work</em><br/>
          </h1>
          <p className="hero-sub">
            AgentMart is the only AI agent marketplace where setup is part of the deal.
            Vetted listings, clear requirements, hands-on help if you need it.
          </p>
          <div className="hero-ctas">
            <button className="btn btn-primary" onClick={() => onCta('buyer')}>
              Get early access <Ico.arrow />
            </button>
            <button className="btn btn-secondary" onClick={() => onCta('seller')}>
              Apply as a seller
            </button>
          </div>
          <div className="hero-meta">
            <span>Verified listings</span>
            <span className="sep"/>
            <span>Setup guide included</span>
            <span className="sep"/>
            <span>Assisted deployment available</span>
          </div>
        </div>
        <div className="hero-rail">
          <div className="cell">
            <span className="k">Sectors</span>
            <span className="v">Sales · Finance · Support · Legal · Ops</span>
          </div>
          <div className="cell">
            <span className="k">Listings</span>
            <span className="v">Reviewed before going live</span>
          </div>
          <div className="cell">
            <span className="k">Pricing</span>
            <span className="v">One-time · no subscriptions</span>
          </div>
          <div className="cell">
            <span className="k">Cohort</span>
            <span className="v">01 — Fall 2026</span>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Problem ────────────────────────────────────────────────────────────────
const PROBLEMS = [
  {
    n: "01",
    title: "You can't tell what an agent actually needs until it's too late.",
    body: "Every agent demo looks clean. Then you buy it and discover it needs five API keys, a cloud account you don't have, and an engineer to wire it together. That information was never on the listing page."
  },
  {
    n: "02",
    title: "Every agent looks the same on a listing page.",
    body: "No reviews from real deployments, no production-readiness signal, no way to tell a working agent from an abandoned side project. Until now."
  },
  {
    n: "03",
    title: "You bought it. Now what?",
    body: "The gap between buying an agent and actually running it in your business is where almost every purchase fails. API keys, environment variables, webhooks, schedulers. Most buyers need help. There's nowhere to get it."
  },
];

function Problem() {
  return (
    <section className="section" id="problem" data-screen-label="02 Problem">
      <div className="wrap">
        <div className="sec-head">
          <div className="sec-num">02 · The gap</div>
          <div>
            <h2 className="sec-title">Agents are everywhere.<br/><em>Making them work</em> is still broken.</h2>
            <p className="sec-lede">
              There are thousands of useful autonomous agents being built right now.
              The infrastructure to find them, trust them, buy them, and actually deploy them
              does not exist yet. AgentMart builds that layer.
            </p>
          </div>
        </div>
        <div className="problems">
          {PROBLEMS.map((p) => (
            <div className="problem" key={p.n}>
              <div className="problem-num">{p.n}</div>
              <h3 className="problem-title">{p.title}</h3>
              <p className="problem-body">{p.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Categories() {
  const items = [
    'Outbound research', 'Contract diligence', 'Financial close', 'Support triage',
    'Lead enrichment', 'Compliance monitoring', 'Recruiting screen', 'Pricing audits',
    'Document extraction', 'Vendor onboarding', 'Inventory forecasting', 'Bug triage',
    'QA regression', 'Email summarization', 'Renewal forecasting',
  ];
  const repeated = [...items, ...items];
  return (
    <div className="marquee-strip" aria-label="Workflow categories">
      <div className="label"><span className="dot"/>Workflows</div>
      <div className="marquee-track">
        {repeated.map((it, i) => (
          <React.Fragment key={i}>
            <span className={'item' + (i % 3 === 1 ? ' muted' : '')}>{it}</span>
            <span className="sep" aria-hidden="true"/>
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

// ── Solution ───────────────────────────────────────────────────────────────
const SOLUTIONS = [
  {
    n: "01",
    icon: <Ico.curate/>,
    title: "Every agent is reviewed before it goes live.",
    body: "We check for production-readiness, working documentation, and accurate dependency declarations. If it's not ready to run, it doesn't get listed."
  },
  {
    n: "02",
    icon: <Ico.spec/>,
    title: "Setup requirements on the listing page, not buried in a readme.",
    body: "Required API keys, services, technical skill level, and estimated deploy time are declared upfront. You know what you're getting into before you pay."
  },
  {
    n: "03",
    icon: <Ico.pay/>,
    title: "One payment. You own it.",
    body: "No subscriptions, no seat counts, no recurring fees. Buy the agent once, receive the files and setup guide immediately. Stripe handles checkout, invoices, and weekly payouts to sellers."
  },
  {
    n: "04",
    icon: <Ico.hand/>,
    title: "Stuck on deployment? The builder will do it for you.",
    body: "Every listing can offer an assisted setup add-on. You pay the developer who built it to configure and deploy it in your environment. The last mile, handled."
  },
];

function Solution() {
  return (
    <section className="section" id="solution" data-screen-label="03 Solution">
      <div className="wrap">
        <div className="sec-head">
          <div className="sec-num">03 · How it works</div>
          <div>
            <h2 className="sec-title">A marketplace that treats agents like <em>real software</em>.</h2>
            <p className="sec-lede">
              Not a directory. Not a prompt store. A transactional marketplace with a quality bar,
              clear specifications, integrated payments, and a path to deployment for every buyer
              regardless of their technical level.
            </p>
          </div>
        </div>
        <div className="solutions">
          {SOLUTIONS.map((s) => (
            <div className="solution" key={s.n}>
              <div className="solution-head">
                <div className="solution-icon">{s.icon}</div>
                <div className="solution-num">{s.n} / 04</div>
              </div>
              <div>
                <h3 className="solution-title">{s.title}</h3>
                <p className="solution-body">{s.body}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ── Audience: Buyers + Sellers ─────────────────────────────────────────────
const BUYER_FEATURES = [
  {
    t: "Know exactly what you're buying before checkout.",
    s: "Every listing declares required tools, API keys, technical skill level, and estimated setup time. No surprises after payment."
  },
  {
    t: "Not technical? That's fine.",
    s: "Filter by technical level. listings marked 'non-technical setup' include step-by-step guides written for operators, not engineers."
  },
  {
    t: "Files, guide, and configuration delivered instantly.",
    s: "On purchase you receive the agent, setup runbook, and all required configuration — directly, no back-and-forth with the seller."
  },
  {
    t: "Pay the builder to deploy it for you.",
    s: "If you need help, the developer who built the agent is available for an assisted setup. Booked and paid in-platform."
  },
  {
    t: "Search by what you need done, not by technology.",
    s: "Filter by department, workflow type, and integration requirements — not model names or frameworks you don't recognise."
  },
];

const SELLER_FEATURES = [
  {
    t: "Stop selling by email. List once, sell to hundreds.",
    s: "Your agent becomes a product with its own page, pricing, spec sheet, and checkout. No more scoping calls for every new customer."
  },
  {
    t: "Stripe-backed payouts, every week.",
    s: "Payments, invoices, and tax collection are handled. You build the agent — we handle the money."
  },
  {
    t: "Charge extra for setup. Keep the revenue.",
    s: "Add an assisted setup SKU to any listing. Buyers who need deployment help pay you directly through the platform."
  },
  {
    t: "A listing page built for software, not for creators.",
    s: "Version history, production-readiness badge, dependency spec, sample runs, and verified reviews from real deployments."
  },
  {
    t: "Founding sellers get placement priority at launch.",
    s: "The first cohort of verified sellers is featured across all discovery surfaces when the marketplace opens publicly."
  },
];

function AudienceSide({ tag, eyebrow, title, body, features, cta, onCta }) {
  return (
    <div className="audience-side">
      <div className="audience-tag">
        <span className="pill">{tag}</span>
        <span>{eyebrow}</span>
      </div>
      <h3 className="audience-title">{title}</h3>
      <p className="audience-body">{body}</p>
      <ul className="feature-list">
        {features.map((f, i) => (
          <li key={i}>
            <span className="tick"><Ico.check/></span>
            <div>
              <div>{f.t}</div>
              <div className="sub">{f.s}</div>
            </div>
          </li>
        ))}
      </ul>
      <div>
        <button className="btn btn-primary" onClick={onCta}>{cta} <Ico.arrow/></button>
      </div>
    </div>
  );
}

function Audience({ onCta }) {
  return (
    <section className="section" style={{padding: 0}}>
      <div className="wrap">
        <div className="sec-head" style={{padding: '96px 0 0'}}>
          <div className="sec-num">04 · Who it's for</div>
          <div>
            <h2 className="sec-title">Two sides. <em>One</em> standard.</h2>
            <p className="sec-lede">
              Early access is open to a curated group of buyers and a hand-picked cohort of founding sellers.
              Both sides are reviewed individually.
            </p>
          </div>
        </div>
        <div className="audience" id="buyers" data-screen-label="04 Audience">
          <AudienceSide
            tag="01 / Buyers"
            title={<>For anyone who wants the <em>result</em>, not the engineering sprint.</>}
            body="Whether you're a solo founder or a team lead cutting repetitive work, you don't need an engineer. Every listing is built for the person running the workflow, not the person maintaining the infrastructure."
            features={BUYER_FEATURES}
            cta="Get buyer early access"
            onCta={() => onCta('buyer')}
          />
  
          <div id="sellers">
            <AudienceSide
              tag="02 / Sellers"
              title={<>For builders who want a <em>product</em>, not a client.</>}
              body="You've shipped an agent that works. Now you want to sell it to more than one person without scoping a new engagement every time. AgentMart is that distribution layer."
              features={SELLER_FEATURES}
              cta="Apply as founding seller"
              onCta={() => onCta('seller')}
            />
          </div>
        </div>
        <div style={{height: 96}}/>
      </div>
    </section>
  );
}

// ── Form ───────────────────────────────────────────────────────────────────
function Form({ initialRole, formRef }) {
  const [role, setRole] = useState(initialRole || 'buyer');
  const [submitted, setSubmitted] = useState(false);
  const [touched, setTouched] = useState(false);
  const [data, setData] = useState({
    email: '', level: '',
    site: '', desc: '', ready: '', guide: '',
  });

  useEffect(() => {
    if (initialRole) setRole(initialRole);
  }, [initialRole]);

  const update = (k) => (e) => setData((d) => ({ ...d, [k]: e.target.value }));

  // Buyer: only email required. Level is optional but useful for us.
  const buyerValid = data.email.includes('@');
  const sellerValid = data.email.includes('@') && data.desc.trim().length > 3;
  const bothValid = buyerValid && sellerValid;
  const valid = role === 'buyer' ? buyerValid : role === 'seller' ? sellerValid : bothValid;

  const submit = (e) => {
    e.preventDefault();
    setTouched(true);
    if (!valid) return;
    setSubmitted(true);
  };

  const ref = useMemo(() => `AM-${Math.floor(100000 + Math.random()*899999)}`, [submitted]);

  return (
    <section className="form-section" id="access" data-screen-label="05 Early Access" ref={formRef}>
      <div className="wrap">
        <div className="form-grid">
          <div className="form-side">
            <div className="eyebrow"><span className="dot"/> Early access</div>
            <h3 style={{marginTop: 20}}>
            Get early access.<br/>You're two <br/> minutes away.
            </h3>
            <p>
            Cohort 01 is opening to a small group of buyers and founding sellers. Pick your side, or both.
            </p>
            <dl className="ledger">
              <div className="ledger-row"><dt>Cohort</dt><dd>01 · Fall 2026</dd></div>
              <div className="ledger-row"><dt>Buyer seats</dt><dd>~250 in first cohort</dd></div>
              <div className="ledger-row"><dt>Seller seats</dt><dd>By application · founding tier</dd></div>
              <div className="ledger-row"><dt>Response time</dt><dd>Within 5 business days</dd></div>
              <div className="ledger-row" style={{borderBottom: 0}}><dt>Commitment</dt><dd>None at signup</dd></div>
            </dl>
          </div>

          <div className="form-card">
            {submitted ? (
              <div className="success">
                <div className="success-mark"><Ico.check style={{width: 16, height: 16, stroke: 'var(--ink)', strokeWidth: 1.6, fill: 'none'}}/></div>
                <h4>You're on the list.</h4>
                <p>
                  We've recorded your interest and will reach out from{' '}
                  <code style={{fontFamily: 'var(--mono)', fontSize: 13}}>access@agentmart.com</code>{' '}
                  when Cohort 01 opens. Applications are reviewed in order of arrival.
                </p>
                <div className="success-meta">REF · {ref}  ·  ROLE · {role.toUpperCase()}</div>
              </div>
            ) : (
              <form onSubmit={submit} noValidate>

                <label className="field-label">I want to</label>
                <div className="seg" role="tablist">
                  {['buyer', 'seller', 'both'].map((r) => (
                    <button
                      key={r}
                      type="button"
                      role="tab"
                      aria-selected={role === r}
                      onClick={() => setRole(r)}
                    >
                      <span className="seg-dot"/>
                      {r === 'both' ? 'Buy & sell' : r === 'buyer' ? 'Buy agents' : 'Sell agents'}
                    </button>
                  ))}
                </div>

                <div style={{height: 24}}/>

                <div className="form-row">
                  <label className="field-label">email</label>
                  <input className="input" type="email" required placeholder="you@company.com"
                         value={data.email} onChange={update('email')} />
                </div>

                {(role === 'buyer' || role === 'both') && (
                  <>
                    <div className="form-row">
                      <label className="field-label">
                        Your technical level <span style={{fontWeight: 400, opacity: 0.5}}>(optional — helps us match you with the right agents)</span>
                      </label>
                      <select className="select" value={data.level} onChange={update('level')}>
                        <option value="">Select…</option>
                        <option>Non-technical — I run the business side</option>
                        <option>Some technical — ops, RevOps, or analyst</option>
                        <option>Engineering team available</option>
                      </select>
                    </div>
                  </>
                )}

                {(role === 'seller' || role === 'both') && (
                  <>
                    <div className="form-row">
                      <label className="field-label">Website, GitHub, or portfolio</label>
                      <input className="input" type="text" placeholder="https://"
                             value={data.site} onChange={update('site')} />
                    </div>
                    <div className="form-row">
                      <label className="field-label">Describe your agent</label>
                      <textarea className="textarea" placeholder="What does it do, who is it for, and how does it run? One paragraph is enough."
                                value={data.desc} onChange={update('desc')} />
                    </div>
                    <div className="form-row split">
                      <div>
                        <label className="field-label">Production status</label>
                        <select className="select" value={data.ready} onChange={update('ready')}>
                          <option value="">Select…</option>
                          <option>Live with a paying customer</option>
                          <option>Used internally, ready to ship</option>
                          <option>Prototype — not yet deployed</option>
                        </select>
                      </div>
                      <div>
                        <label className="field-label">Setup guide exists?</label>
                        <select className="select" value={data.guide} onChange={update('guide')}>
                          <option value="">Select…</option>
                          <option>Yes — written and tested</option>
                          <option>Draft only</option>
                          <option>Not yet</option>
                        </select>
                      </div>
                    </div>
                  </>
                )}

                <div className="form-foot">
                  <div className="note">
                    By submitting you agree to be contacted about Cohort 01. No spam, no selling your data.
                    {touched && !valid && (
                      <div style={{color: 'oklch(0.55 0.16 25)', marginTop: 6}}>
                        {role === 'seller' || role === 'both'
                          ? 'Add your email and a description of your agent to continue.'
                          : 'Add your email to continue.'}
                      </div>
                    )}
                  </div>
                  <button type="submit" className="btn btn-primary">
                    Request access <Ico.arrow/>
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="foot">
      <div className="wrap foot-row">
        <div className="brand">
          <span className="brand-mark" aria-hidden="true">
            <img src="agentmart_favicon.svg" alt="" />
          </span>
          <span className="brand-name">Agent<em>Mart</em></span>
        </div>
        <div className="foot-meta">
          © 2026 AgentMart ·{' '}
          <a href="mailto:canepanerifilippo@gmail.com" style={{color: 'inherit', textDecoration: 'none'}}>
            Contact Us
          </a>
        </div>
        <div className="foot-meta">v0.1 · pre-launch</div>
      </div>
    </footer>
  );
}

// ── App ────────────────────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = useTweaks(window.__TWEAK_DEFAULTS__);
  const [role, setRole] = useState('buyer');
  const formRef = useRef(null);

  const onCta = (r) => {
    setRole(r);
    requestAnimationFrame(() => {
      formRef.current?.scrollIntoView ? null : null;
      const top = formRef.current?.getBoundingClientRect().top + window.scrollY - 24;
      if (top != null) window.scrollTo({ top, behavior: 'smooth' });
    });
  };

  const b1 = t.brand1 || '#7b6cf6';
  const b2 = t.brand2 || '#4facfe';
  const cssVars = {
    '--brand-1': b1,
    '--brand-2': b2,
    '--brand-grad': `linear-gradient(120deg, ${b1} 0%, ${b2} 100%)`,
    '--accent': b1,
    '--accent-ink': b1,
    '--display': `'${t.display}', 'Times New Roman', serif`,
  };

  return (
    <div style={cssVars}>
      <Nav onCta={onCta} />
      <Hero onCta={onCta} brand1={b1} brand2={b2} />
      <Categories />
      <Problem />
      <Solution />
      <Audience onCta={onCta} />
      <Form initialRole={role} formRef={formRef} />
      <Footer />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Brand gradient">
          <TweakColor
            label="Gradient"
            value={[t.brand1, t.brand2]}
            options={[
              ["#7b6cf6", "#4facfe"],
              ["#8b5cf6", "#22d3ee"],
              ["#6d28d9", "#7b6cf6"],
              ["#0f0e17", "#3a3848"],
              ["#a78bfa", "#f0abfc"],
            ]}
            onChange={(v) => setTweak({ brand1: v[0], brand2: v[1] })}
          />
          <TweakColor
            label="Start"
            value={t.brand1}
            onChange={(v) => setTweak('brand1', v)}
          />
          <TweakColor
            label="End"
            value={t.brand2}
            onChange={(v) => setTweak('brand2', v)}
          />
        </TweakSection>
        <TweakSection label="Typography">
          <TweakSelect
            label="Display"
            value={t.display}
            options={["Syne", "Instrument Serif", "Newsreader", "Geist"]}
            onChange={(v) => setTweak('display', v)}
          />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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