/* global React, Icons, GlowOrbs, OrionData, SectionHead, ACCENT, Logo, Wordmark */
const { useState: useSB, useEffect: useEB, useRef: useRB } = React;

// ---------- Selected Work ----------
function WorkCard({ item, onOpen, delay }) {
  const a = ACCENT[item.accent];
  return (
    <button onClick={() => onOpen(item)}
      className="reveal group text-left relative rounded-2xl glass card-lift overflow-hidden p-6 hover:border-white/12 focus-visible:border-white/20"
      style={{ transitionDelay: `${delay}ms` }}>
      <div className="absolute -top-20 -right-16 w-52 h-52 rounded-full blur-3xl opacity-0 group-hover:opacity-100 transition-opacity duration-500" style={{ background: `radial-gradient(circle, ${a.soft}, transparent 70%)` }} />
      <div className="relative">
        <div className="flex items-center justify-between mb-6">
          <div>
            <div className="font-display font-semibold text-heading text-[15px]">{item.client}</div>
            <div className="text-[12px] text-body-dim font-mono mt-0.5">{item.sector}</div>
          </div>
          <span className="w-9 h-9 rounded-full grid place-items-center glass-strong text-body group-hover:text-heading transition-colors" style={{ boxShadow: `inset 0 0 0 1px ${a.ring}` }}>
            <Icons.ArrowUpRight size={16} />
          </span>
        </div>
        <div className="flex items-baseline gap-2 mb-1">
          <span className="font-display font-bold text-[clamp(2rem,4vw,2.6rem)] leading-none" style={{ color: a.dot }}>{item.metric}</span>
          <span className="text-[13px] text-body font-mono">{item.metricLabel}</span>
        </div>
        <p className="mt-4 text-[15px] leading-snug text-body group-hover:text-heading/90 transition-colors">{item.title}</p>
        <div className="mt-5 flex flex-wrap gap-2">
          {item.tags.map(t => (
            <span key={t} className="text-[11px] font-mono text-body-dim px-2 py-1 rounded-md bg-white/[0.03] border border-white/5">{t}</span>
          ))}
        </div>
        <div className="mt-5 flex items-center gap-1.5 text-[13px] font-medium" style={{ color: a.dot }}>
          Read case study <Icons.Arrow size={14} className="group-hover:translate-x-1 transition-transform" />
        </div>
      </div>
    </button>
  );
}

function CaseStudyModal({ item, onClose, onCta }) {
  useEB(() => {
    const k = (e) => e.key === 'Escape' && onClose();
    document.addEventListener('keydown', k);
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', k); document.body.style.overflow = ''; };
  }, []);
  if (!item) return null;
  const a = ACCENT[item.accent];
  const blocks = [
    ['The problem', item.problem, 'Search'],
    ['What we built', item.built, 'Hammer'],
    ['The result', item.result, 'TrendUp'],
  ];
  return (
    <div className="fixed inset-0 z-[60] flex items-end sm:items-center justify-center p-0 sm:p-6">
      <div className="absolute inset-0 bg-ink/85 backdrop-blur-sm animate-[fadeIn_.2s_ease]" onClick={onClose} style={{ animation: 'fadeIn .2s ease' }} />
      <div role="dialog" aria-modal="true" aria-label={item.client + ' case study'}
        className="relative w-full sm:max-w-2xl max-h-[92vh] sm:max-h-[88vh] overflow-y-auto glass-strong rounded-t-3xl sm:rounded-3xl shadow-2xl"
        style={{ animation: 'slideUp .28s cubic-bezier(.2,.7,.2,1)' }}>
        {/* header */}
        <div className="sticky top-0 z-10 flex items-center justify-between px-6 sm:px-8 py-4 border-b border-white/8 glass-strong">
          <div className="flex items-center gap-3 min-w-0">
            <span className="w-9 h-9 rounded-xl grid place-items-center shrink-0" style={{ background: a.soft, boxShadow: `inset 0 0 0 1px ${a.ring}` }}>
              <span className="w-2 h-2 rounded-full" style={{ background: a.dot }} />
            </span>
            <div className="min-w-0">
              <div className="font-display font-semibold text-heading truncate">{item.client}</div>
              <div className="text-[11px] text-body-dim font-mono truncate">{item.sector}</div>
            </div>
          </div>
          <button onClick={onClose} className="w-9 h-9 grid place-items-center rounded-xl btn-ghost text-heading shrink-0" aria-label="Close"><Icons.X size={18} /></button>
        </div>

        <div className="px-6 sm:px-8 py-6">
          <h3 className="font-display font-bold text-heading text-[22px] sm:text-[26px] leading-tight">{item.title}</h3>
          {/* stat band */}
          <div className="mt-5 grid grid-cols-3 gap-3">
            {item.stats.map(([v, l]) => (
              <div key={l} className="rounded-xl glass p-3 text-center">
                <div className="font-display font-bold text-[clamp(1.2rem,4vw,1.6rem)] leading-none" style={{ color: a.dot }}>{v}</div>
                <div className="text-[11px] text-body-dim mt-1.5 leading-tight">{l}</div>
              </div>
            ))}
          </div>
          {/* blocks */}
          <div className="mt-7 space-y-6">
            {blocks.map(([h, body, ic]) => (
              <div key={h} className="flex gap-4">
                <span className="w-9 h-9 rounded-lg grid place-items-center glass shrink-0 mt-0.5">
                  {React.createElement(Icons[ic], { size: 17, className: a.text })}
                </span>
                <div>
                  <div className="text-[12px] font-mono uppercase tracking-wide text-body-dim mb-1.5">{h}</div>
                  <p className="text-[15px] leading-relaxed text-body">{body}</p>
                </div>
              </div>
            ))}
          </div>
          <button onClick={() => { onClose(); onCta(); }} className="mt-8 w-full btn-primary text-white font-medium px-5 py-3.5 rounded-xl flex items-center justify-center gap-2">
            Start a project like this <Icons.Arrow size={17} />
          </button>
        </div>
      </div>
    </div>
  );
}

function Work({ onCta }) {
  const [active, setActive] = useSB(null);
  return (
    <section id="work" className="py-20 sm:py-28 relative">
      <div className="max-w-7xl mx-auto px-4 sm:px-6">
        <SectionHead kicker="Selected work" title="Shipped, in production, with the numbers to prove it." sub="Three recent builds. Every one is live, every metric is real to the engagement. Click any card for the full story." />
        <div className="mt-12 grid md:grid-cols-3 gap-4">
          {OrionData.WORK.map((w, i) => <WorkCard key={w.id} item={w} onOpen={setActive} delay={i * 80} />)}
        </div>
      </div>
      {active && <CaseStudyModal item={active} onClose={() => setActive(null)} onCta={onCta} />}
    </section>
  );
}

// ---------- Process ----------
function Process() {
  return (
    <section id="process" className="py-20 sm:py-28 relative overflow-hidden">
      <GlowOrbs className="opacity-30" />
      <div className="max-w-7xl mx-auto px-4 sm:px-6 relative">
        <SectionHead center kicker="How we work" title="A simple arc. Relentless delivery." sub="No black boxes, no month-long silences. Weekly demos from week one, and we stay on after launch." />
        <div className="mt-14 grid sm:grid-cols-2 lg:grid-cols-4 gap-4 relative">
          <div className="hidden lg:block absolute top-[34px] left-[12%] right-[12%] h-px bg-gradient-to-r from-violet-500/0 via-violet-500/30 to-cyan-500/0" />
          {OrionData.PROCESS.map((p, i) => (
            <div key={p.step} className="reveal relative" style={{ transitionDelay: `${i * 90}ms` }}>
              <div className="flex flex-col items-center text-center lg:items-start lg:text-left">
                <div className="relative mb-5">
                  <span className="w-[68px] h-[68px] rounded-2xl grid place-items-center glass-strong relative z-10" style={{ boxShadow: 'inset 0 0 0 1px rgba(139,92,246,0.3)' }}>
                    {React.createElement(Icons[p.icon], { size: 26, className: 'text-violet-300' })}
                  </span>
                  <span className="absolute -top-2 -right-2 z-20 w-7 h-7 rounded-full grid place-items-center font-mono text-[11px] text-white" style={{ background: 'linear-gradient(135deg,#6366F1,#8B5CF6)' }}>{p.step}</span>
                </div>
                <span className="text-[11px] font-mono text-cyan mb-1.5">{p.dur}</span>
                <h3 className="font-display font-semibold text-heading text-[19px] mb-2">{p.title}</h3>
                <p className="text-[14px] leading-relaxed text-body">{p.desc}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Metrics band ----------
function Metrics() {
  return (
    <section className="py-12 relative">
      <div className="max-w-7xl mx-auto px-4 sm:px-6">
        <div className="reveal rounded-2xl glass-strong overflow-hidden relative grad-border">
          <div className="absolute inset-0 grid-faint opacity-40" />
          <div className="relative grid grid-cols-2 lg:grid-cols-4 divide-x divide-y lg:divide-y-0 divide-white/6">
            {OrionData.METRICS.map((m) => (
              <div key={m.label} className="p-7 sm:p-9 text-center">
                <div className="font-display font-bold text-heading text-[clamp(2rem,5vw,3rem)] leading-none">
                  <span className="text-gradient-tight">{m.value}</span>
                </div>
                <div className="mt-2.5 text-[13px] text-body font-mono uppercase tracking-wide">{m.label}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- About ----------
function About() {
  return (
    <section id="about" className="py-20 sm:py-28 relative">
      <div className="max-w-7xl mx-auto px-4 sm:px-6">
        <div className="grid lg:grid-cols-[1fr_0.85fr] gap-10 lg:gap-16 items-center">
          <div className="reveal">
            <SectionHead kicker="About Orion" title="A founder-led studio, not a body shop." />
            <div className="mt-6 space-y-4 text-[16px] leading-relaxed text-body max-w-xl">
              <p>Orion Technologies is a US-registered AI engineering studio. We're small on purpose — a senior team that takes a handful of engagements at a time and treats each one like our own product.</p>
              <p>We've spent six years shipping AI into production: dashboards people open every morning, SaaS products carrying real load, and agent fleets running operations at 3am. We know the difference between an impressive demo and software that survives contact with users — and we only build the second kind.</p>
            </div>
            <div className="mt-7 flex flex-wrap gap-2.5">
              {['Senior-only team', 'Weekly demos', 'Production-grade', 'We stay after launch'].map(t => (
                <span key={t} className="flex items-center gap-2 text-[13px] text-body px-3 py-2 rounded-xl glass">
                  <Icons.Check size={14} className="text-mint" />{t}
                </span>
              ))}
            </div>
          </div>
          {/* founder card */}
          <div className="reveal" style={{ transitionDelay: '120ms' }}>
            <div className="rounded-2xl glass-strong p-2 grad-border">
              <div className="rounded-xl overflow-hidden">
                <div className="aspect-[4/3] relative grid place-items-center" style={{ background: 'repeating-linear-gradient(135deg,#0e1422,#0e1422 11px,#101728 11px,#101728 22px)' }}>
                  <div className="absolute inset-0" style={{ background: 'radial-gradient(circle at 50% 40%, rgba(99,102,241,0.25), transparent 70%)' }} />
                  <div className="text-center relative">
                    <div className="w-16 h-16 mx-auto rounded-2xl bg-gradient-to-br from-violet-500 to-cyan-400 grid place-items-center text-white" style={{ boxShadow: '0 10px 30px -8px rgba(99,102,241,0.6)' }}>
                      <Icons.Users size={28} />
                    </div>
                    <div className="mt-3 font-mono text-[11px] text-body-dim uppercase tracking-widest">our team</div>
                  </div>
                </div>
              </div>
              <div className="p-5">
                <div className="font-display font-semibold text-heading text-[17px]">The Orion team</div>
                <div className="text-[13px] text-body-dim mt-0.5">Senior engineers, designers and operators</div>
                <p className="mt-3 text-[14px] leading-relaxed text-body">"We started Orion to do the work we'd want as clients: senior people, honest timelines, and software that ships."</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Testimonials ----------
function Testimonials() {
  return (
    <section className="py-20 sm:py-28 relative overflow-hidden">
      <GlowOrbs className="opacity-30" />
      <div className="max-w-7xl mx-auto px-4 sm:px-6 relative">
        <SectionHead center kicker="Testimonials" title="Founders and operators who'd hire us again." />
        <div className="mt-12 grid md:grid-cols-3 gap-4">
          {OrionData.TESTIMONIALS.map((t, i) => {
            const a = ACCENT[t.accent];
            return (
              <figure key={t.name} className="reveal rounded-2xl glass card-lift p-6 flex flex-col" style={{ transitionDelay: `${i * 80}ms` }}>
                <div className="flex gap-1 mb-4">
                  {Array.from({ length: 5 }).map((_, j) => <Icons.Star key={j} size={15} className="text-amber-400" style={{ fill: '#FBBF24' }} />)}
                </div>
                <blockquote className="text-[15px] leading-relaxed text-heading/90 flex-1">"{t.quote}"</blockquote>
                <figcaption className="mt-6 flex items-center gap-3">
                  <span className="w-10 h-10 rounded-full grid place-items-center text-white text-[13px] font-semibold shrink-0" style={{ background: `linear-gradient(135deg, ${a.dot}, #6366F1)` }}>{t.initials}</span>
                  <div>
                    <div className="text-[14px] font-medium text-heading">{t.name}</div>
                    <div className="text-[12px] text-body-dim">{t.role}</div>
                  </div>
                </figcaption>
              </figure>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ---------- Final CTA + Contact ----------
function Contact({ formRef }) {
  const [form, setForm] = useSB({ name: '', email: '', company: '', budget: 'Exploring', message: '' });
  const [errors, setErrors] = useSB({});
  const [status, setStatus] = useSB('idle'); // idle | submitting | success

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Please tell us your name';
    if (!form.email.trim()) e.email = 'We need an email to reply';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'That email looks off';
    if (!form.message.trim() || form.message.trim().length < 12) e.message = 'A sentence or two about your project helps';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setStatus('submitting');
    setTimeout(() => setStatus('success'), 1800);
  };

  const field = (name, label, props = {}) => (
    <div>
      <label htmlFor={name} className="block text-[13px] text-body mb-1.5">{label}</label>
      <input id={name} value={form[name]} onChange={e => setForm(f => ({ ...f, [name]: e.target.value }))}
        className={`w-full rounded-xl bg-white/[0.03] border px-4 py-3 text-[15px] text-heading placeholder:text-body-dim outline-none transition-colors focus:border-violet-400/60 focus:bg-white/[0.05] ${errors[name] ? 'border-rose-400/60' : 'border-white/8'}`}
        {...props} />
      {errors[name] && <p className="mt-1.5 text-[12px] text-rose-400">{errors[name]}</p>}
    </div>
  );

  return (
    <section id="contact" ref={formRef} className="py-20 sm:py-28 relative scroll-mt-24">
      <div className="max-w-7xl mx-auto px-4 sm:px-6">
        {/* CTA band */}
        <div className="reveal relative rounded-3xl overflow-hidden glass-strong mb-14">
          <div className="absolute inset-0" style={{ background: 'linear-gradient(120deg, rgba(99,102,241,0.22), rgba(139,92,246,0.12) 50%, rgba(34,211,238,0.14))' }} />
          <div className="absolute -top-20 left-1/3 w-96 h-96 rounded-full blur-3xl opacity-50" style={{ background: 'radial-gradient(circle,rgba(139,92,246,0.5),transparent 70%)' }} />
          <div className="relative px-6 sm:px-12 py-12 sm:py-16 text-center">
            <h2 className="font-display font-bold text-heading text-[clamp(2rem,5vw,3.25rem)] leading-[1.05] tracking-tight">Let's build your AI product.</h2>
            <p className="mt-4 text-[17px] text-body max-w-xl mx-auto">Tell us what you're trying to ship. We'll reply within 24 hours with a clear next step — no sales theatre.</p>
            <a href="#contact-form" className="mt-8 inline-flex btn-primary text-white font-medium px-7 py-3.5 rounded-xl items-center gap-2 text-[15px]">
              Book a call <Icons.Arrow size={17} />
            </a>
          </div>
        </div>

        {/* contact grid */}
        <div id="contact-form" className="grid lg:grid-cols-[0.85fr_1.15fr] gap-10 lg:gap-14 scroll-mt-28">
          <div className="reveal">
            <SectionHead kicker="Contact" title="Start a conversation." />
            <p className="mt-5 text-[16px] leading-relaxed text-body">Prefer email or phone? Reach us directly — our team reads every message.</p>
            <div className="mt-7 space-y-3">
              {[['Mail', 'hello@myoriontechnologies.com', 'mailto:hello@myoriontechnologies.com'], ['Pin', '5203 Juan Tabo Blvd NE, Suite 2b · Albuquerque, NM 87111', null]].map(([ic, t, href]) => (
                <a key={t} href={href || undefined} className={`flex items-center gap-3.5 p-3.5 rounded-xl glass ${href ? 'hover:border-white/14 transition-colors' : ''}`}>
                  <span className="w-10 h-10 rounded-lg grid place-items-center glass-strong text-violet-300 shrink-0">{React.createElement(Icons[ic], { size: 18 })}</span>
                  <span className="text-[14px] text-body">{t}</span>
                </a>
              ))}
            </div>
            <div className="mt-6 flex items-center gap-2 text-[13px] text-body">
              <span className="w-2 h-2 rounded-full bg-mint animate-pulse-dot" /> Currently booking projects for Q3 2026
            </div>
          </div>

          {/* form */}
          <div className="reveal" style={{ transitionDelay: '100ms' }}>
            <div className="rounded-2xl glass-strong p-6 sm:p-8 relative grad-border min-h-[440px] flex">
              {status === 'success' ? (
                <div className="m-auto text-center py-8">
                  <div className="w-16 h-16 mx-auto rounded-2xl grid place-items-center mb-5" style={{ background: 'linear-gradient(135deg,#34D399,#22D3EE)' }}>
                    <Icons.Check size={30} className="text-ink" stroke={2.4} />
                  </div>
                  <h3 className="font-display font-bold text-heading text-[24px]">Message received.</h3>
                  <p className="mt-3 text-[15px] text-body max-w-sm mx-auto">Thanks, {form.name.split(' ')[0] || 'there'}. Our team will reply to <span className="text-heading">{form.email}</span> within 24 hours.</p>
                  <button onClick={() => { setStatus('idle'); setForm({ name: '', email: '', company: '', budget: 'Exploring', message: '' }); }}
                    className="mt-7 btn-ghost text-heading font-medium px-5 py-3 rounded-xl">Send another</button>
                </div>
              ) : (
                <form onSubmit={submit} noValidate className="w-full space-y-4">
                  <div className="grid sm:grid-cols-2 gap-4">
                    {field('name', 'Your name', { placeholder: 'Jordan Lee', autoComplete: 'name' })}
                    {field('email', 'Work email', { placeholder: 'jordan@company.com', type: 'email', autoComplete: 'email' })}
                  </div>
                  {field('company', 'Company (optional)', { placeholder: 'Acme Inc.' })}
                  <div>
                    <label className="block text-[13px] text-body mb-1.5">Budget range</label>
                    <div className="flex flex-wrap gap-2">
                      {['Exploring', '$10–25k', '$25–75k', '$75k+'].map(b => (
                        <button type="button" key={b} onClick={() => setForm(f => ({ ...f, budget: b }))}
                          className={`px-3.5 py-2 rounded-xl text-[13px] border transition-colors ${form.budget === b ? 'text-white border-transparent btn-primary' : 'text-body border-white/8 bg-white/[0.03] hover:border-white/16'}`}>{b}</button>
                      ))}
                    </div>
                  </div>
                  <div>
                    <label htmlFor="message" className="block text-[13px] text-body mb-1.5">What are you building?</label>
                    <textarea id="message" rows={4} value={form.message} onChange={e => setForm(f => ({ ...f, message: e.target.value }))}
                      placeholder="We want to add an AI assistant to our ops dashboard…"
                      className={`w-full rounded-xl bg-white/[0.03] border px-4 py-3 text-[15px] text-heading placeholder:text-body-dim outline-none transition-colors resize-none focus:border-violet-400/60 focus:bg-white/[0.05] ${errors.message ? 'border-rose-400/60' : 'border-white/8'}`} />
                    {errors.message && <p className="mt-1.5 text-[12px] text-rose-400">{errors.message}</p>}
                  </div>
                  <button type="submit" disabled={status === 'submitting'}
                    className="w-full btn-primary text-white font-medium px-5 py-3.5 rounded-xl flex items-center justify-center gap-2 disabled:opacity-80">
                    {status === 'submitting'
                      ? <><span className="w-4 h-4 rounded-full border-2 border-white/30 border-t-white animate-spin-slow" /> Sending…</>
                      : <>Send message <Icons.Arrow size={17} /></>}
                  </button>
                  <p className="text-[12px] text-body-dim text-center">Design demo · no message is actually sent.</p>
                </form>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Footer ----------
function Footer({ onCta }) {
  const cols = [
    ['Product', [['Orion Ops', '#product'], ['AI agents', '#services'], ['Dashboards', '#services'], ['Integrations', '#product']]],
    ['Company', [['About', '#about'], ['Selected work', '#work'], ['Process', '#process'], ['Careers', '#contact']]],
    ['Resources', [['Case studies', '#work'], ['Tech stack', '#top'], ['Book a call', '#contact'], ['Blog', '/blog/']]],
    ['Legal', [['Privacy', '/privacy.html'], ['Terms', '/terms.html'], ['Cookies', '/cookies.html']]],
  ];
  return (
    <footer className="relative border-t border-white/6 pt-16 pb-8 overflow-hidden">
      <div className="absolute -top-32 left-1/2 -translate-x-1/2 w-[40rem] h-64 rounded-full blur-3xl opacity-30" style={{ background: 'radial-gradient(circle,rgba(99,102,241,0.4),transparent 70%)' }} />
      <div className="max-w-7xl mx-auto px-4 sm:px-6 relative">
        <div className="grid lg:grid-cols-[1.4fr_2fr] gap-10 pb-12 border-b border-white/6">
          <div>
            <Wordmark />
            <p className="mt-4 text-[14px] leading-relaxed text-body max-w-xs">We build AI products that ship. Strategy, build, operate — for teams that want real AI without an in-house team.</p>
            <button onClick={onCta} className="mt-6 btn-primary text-white text-[14px] font-medium px-5 py-3 rounded-xl inline-flex items-center gap-2">Book a call <Icons.Arrow size={15} /></button>
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-8">
            {cols.map(([h, links]) => (
              <div key={h}>
                <div className="text-[12px] font-mono uppercase tracking-widest text-body-dim mb-4">{h}</div>
                <ul className="space-y-2.5">
                  {links.map(([l, href]) => (
                    <li key={l}><a href={href} className="text-[14px] text-body hover:text-heading transition-colors">{l}</a></li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </div>
        <div className="pt-7 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-5">
          <p className="text-[12.5px] text-body-dim leading-relaxed">© 2026 Orion Technologies LLC — 5203 Juan Tabo Blvd NE, Suite 2b, Albuquerque, NM 87111 · New Mexico LLC</p>
          <div className="flex items-center gap-2">
            {['Code', 'Users', 'Mail', 'Activity'].map((ic, i) => (
              <a key={i} href="#contact" className="w-9 h-9 rounded-lg grid place-items-center glass text-body hover:text-heading transition-colors" aria-label="social link">
                {React.createElement(Icons[ic], { size: 16 })}
              </a>
            ))}
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Work, Process, Metrics, About, Testimonials, Contact, Footer, CaseStudyModal });
