// Sections: Hero, Problem, How It Works, Industries, Credibility, Audit Form, Contact, Footer

// ---------- Logo ----------
const BrikLogo = ({ dark = false, size = 'md' }) => {
  const text = size === 'lg' ? 'text-2xl' : 'text-xl';
  return (
    <div className={`brik-logo flex items-center gap-2 ${dark ? 'text-white' : 'text-[#0D1B2A]'}`}>
      <span className="b-block"><span className="b-letter">B</span></span>
      <span className={`${text} tracking-wide`}>BRIK</span>
    </div>
  );
};

// ---------- Header ----------
const Header = ({ activeSection, onNav }) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const links = [
    { id: 'home', label: 'Home' },
    { id: 'industries', label: 'Industries' },
    { id: 'how', label: 'How It Works' },
    { id: 'audit', label: 'Audit' },
    { id: 'contact', label: 'Contact' },
  ];

  return (
    <header className={`fixed top-0 left-0 right-0 z-40 transition-colors ${scrolled ? 'header-scrolled' : ''}`}>
      <div className="max-w-7xl mx-auto px-5 md:px-8 h-16 md:h-20 flex items-center justify-between">
        <a href="#home" onClick={(e)=>{e.preventDefault(); onNav('home');}}>
          <BrikLogo dark={!scrolled} />
        </a>
        <nav className="hidden md:flex items-center gap-1">
          {links.map(l => (
            <a key={l.id} href={`#${l.id}`}
               onClick={(e)=>{e.preventDefault(); onNav(l.id);}}
               className={`px-3 py-2 text-sm font-medium rounded-lg whitespace-nowrap transition ${
                 scrolled
                   ? `${activeSection===l.id ? 'text-[#0D1B2A]' : 'text-[#0D1B2A]/70 hover:text-[#0D1B2A]'} hover:bg-black/5`
                   : `${activeSection===l.id ? 'text-white' : 'text-white/75 hover:text-white'} hover:bg-white/10`
               }`}>
              {l.label}
            </a>
          ))}
        </nav>
        <div className="flex items-center gap-2">
          <button onClick={()=>onNav('audit')} className="hidden md:inline-flex items-center gap-2 btn-green px-4 py-2.5 rounded-xl text-sm whitespace-nowrap">
            Get your audit <I.ArrowRight size={16}/>
          </button>
          <button onClick={()=>setOpen(o=>!o)} className={`md:hidden p-2 rounded-lg ${scrolled ? 'border border-black/10 text-[#0D1B2A]' : 'border border-white/30 text-white'}`} aria-label="Menu">
            {open ? <I.Close/> : <I.Menu/>}
          </button>
        </div>
      </div>
      {open && (
        <div className="md:hidden bg-white border-t border-black/10 px-5 py-3">
          {links.map(l => (
            <a key={l.id} href={`#${l.id}`} onClick={(e)=>{e.preventDefault(); onNav(l.id); setOpen(false);}} className="block py-2.5 text-[#0D1B2A]/80 font-medium">{l.label}</a>
          ))}
          <button onClick={()=>{onNav('audit'); setOpen(false);}} className="mt-2 w-full btn-green px-4 py-3 rounded-xl text-sm flex items-center justify-center gap-2">
            Get your automation audit <I.ArrowRight size={16}/>
          </button>
        </div>
      )}
    </header>
  );
};

// ---------- Hero ----------
const HERO_VARIANTS = {
  empower: {
    h1a: "Get your team's week back",
    h1b: "from admin work that never ends.",
    sub: "Brik redesigns your business processes and builds the AI agents that run them. The result is shorter cycle times, fewer handoffs, and teams freed from repeat work",
    primary: "Get your automation audit",
    secondary: "See workflows for your industry",
  },
  partner: {
    h1a: "AI that works with your team,",
    h1b: "built for the people doing the work.",
    sub: "Brik is an AI studio founded by engineers from Google and Meta. We help dental and medical offices, real estate firms, law and accounting practices, logistics operators, home service contractors, manufacturers, and aerospace suppliers automate the slow, repetitive parts of the day. Your people stay in charge of the decisions.",
    primary: "Get your automation audit",
    secondary: "See workflows for your industry",
  },
  unlock: {
    h1a: "Recover the hours your business",
    h1b: "is already paying for.",
    sub: "Every office, firm, shop, and crew loses hours to spreadsheets, PDFs, and inboxes. Brik finds those hours, gives them back to your team, and keeps the software you already use. An audit maps exactly where your time goes.",
    primary: "Get your automation audit",
    secondary: "See workflows for your industry",
  },
};

const Hero = ({ onNav, variantKey = "empower" }) => {
  const v = HERO_VARIANTS[variantKey] || HERO_VARIANTS.empower;
  return (
    <section id="home" className="relative min-h-[100vh] md:min-h-[92vh] flex items-center text-white overflow-hidden">
      <HeroScenes/>
      <div className="absolute inset-0 hero-overlay"/>
      <div className="relative max-w-7xl mx-auto px-5 md:px-8 pt-28 pb-20 w-full">
        <div className="max-w-3xl">
          <h1 className="font-display text-4xl sm:text-5xl md:text-6xl lg:text-7xl font-bold leading-[1.05] mb-5">
            {v.h1a}<br/>
            <span className="text-white/70">{v.h1b}</span>
          </h1>
          <p className="text-base md:text-lg text-white/85 leading-relaxed max-w-2xl mb-8">
            {v.sub}
          </p>
          <div className="flex flex-col sm:flex-row gap-3 mb-10">
            <button onClick={()=>onNav('audit')} className="btn-green px-6 py-4 rounded-xl text-base inline-flex items-center justify-center gap-2">
              {v.primary} <I.ArrowRight size={18}/>
            </button>
            <button onClick={()=>onNav('industries')} className="btn-outline px-6 py-4 rounded-xl text-base inline-flex items-center justify-center gap-2">
              {v.secondary} <I.ArrowDown size={16}/>
            </button>
          </div>
          <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm text-white/80">
            <span className="inline-flex items-center gap-2"><I.Check size={16} className="tick"/> Founded by Google &amp; Meta engineers</span>
            <span className="inline-flex items-center gap-2"><I.Pin size={16} className="tick"/> Based in Seattle, WA</span>
            <span className="inline-flex items-center gap-2"><I.Map size={16} className="tick"/> Clients in the US, UK, and Europe</span>
          </div>
        </div>
      </div>
    </section>
  );
};

// ---------- Problem ----------
const Problem = () => {
  const points = [
    { h: "Your staff spends hours on repetitive admin", b: "Entering the same data into several systems, chasing signatures, and reconciling invoices. The work has to get done, but it does not need a person doing it by hand every time." },
    { h: "Generic AI tools leave the hard part to you", b: "A chatbot can answer questions. It cannot connect to your scheduling system, follow up on a stalled claim, or fix a broken handoff. Those gaps take time a small business does not have." },
    { h: "Slow admin costs you money", b: "Insurance checks that take a day, quotes that go out a week late, and invoices that sit unpaid. Each delay shows up in cash flow and in jobs you lose." },
  ];
  return (
    <section className="py-20 md:py-28">
      <div className="max-w-7xl mx-auto px-5 md:px-8">
        <div className="max-w-3xl mb-14">
          <h2 className="font-display text-3xl md:text-5xl font-bold text-[#0D1B2A] leading-tight">
            Your business runs on manual work.<br/>
            <span className="text-[#0D1B2A]/55">Most of it never needed to be manual.</span>
          </h2>
        </div>
        <div className="grid md:grid-cols-3 gap-10">
          {points.map(p => (
            <div key={p.h} className="border-t border-[#0D1B2A]/15 pt-6">
              <h3 className="font-display font-bold text-xl text-[#0D1B2A] mb-2 leading-snug">{p.h}</h3>
              <p className="text-[#0D1B2A]/70 leading-relaxed">{p.b}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ---------- How It Works ----------
const HowItWorks = () => {
  const steps = [
    { t: "Workflow Audit", b: "Over two weeks we map your operations: the software you use, where data moves between systems, and the work your team repeats every day. You keep the report whether or not you hire us." },
    { t: "Opportunity Map", b: "A written report ranks your highest-value automation opportunities by expected savings and effort, so you can see where the money is going." },
    { t: "Agent Deployment", b: "For the workflows you approve, we build and deploy AI agents. They connect to the systems you already run, and your team stays in control." },
    { t: "Measure and Expand", b: "We track time saved, costs reduced, and errors avoided. Then we move on to the next workflows." },
  ];
  return (
    <section id="how" className="py-20 md:py-28 bg-[#F0F0F0]">
      <div className="max-w-7xl mx-auto px-5 md:px-8">
        <div className="max-w-3xl mb-14">
          <h2 className="font-display text-3xl md:text-5xl font-bold text-[#0D1B2A] leading-tight">
            From audit to automation in <span className="text-[#3A86FF]">90 days</span>.
          </h2>
        </div>
        <div className="grid md:grid-cols-4 gap-8">
          {steps.map((s,i)=>(
            <div key={s.t} className="border-t border-[#0D1B2A]/15 pt-6">
              <span className="font-display text-sm font-bold text-[#3A86FF]">0{i+1}</span>
              <h3 className="font-display font-bold text-lg text-[#0D1B2A] mt-3 mb-2 leading-snug">{s.t}</h3>
              <p className="text-sm text-[#0D1B2A]/70 leading-relaxed">{s.b}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ---------- Industries ----------
const Industries = () => {
  const [active, setActive] = React.useState(INDUSTRIES[0].id);
  const ind = INDUSTRIES.find(x => x.id === active);
  return (
    <section id="industries" className="py-20 md:py-28 bg-white">
      <div className="max-w-7xl mx-auto px-5 md:px-8">
        <div className="max-w-3xl mb-10">
          <h2 className="font-display text-3xl md:text-5xl font-bold text-[#0D1B2A] leading-tight mb-3">
            Automation built for <span className="text-[#0D1B2A]/55">how your industry works.</span>
          </h2>
          <p className="text-[#0D1B2A]/70 text-lg leading-relaxed">
            Pick your industry to see which workflows we would automate first.
          </p>
        </div>

        <div className="overflow-x-auto no-scrollbar -mx-5 px-5 mb-8">
          <div className="flex gap-2 min-w-max" role="tablist">
            {INDUSTRIES.map(i => {
              const Ic = I[i.iconKey];
              return (
                <button key={i.id} role="tab" aria-selected={active===i.id} className="tab inline-flex items-center gap-2"
                        data-active={active===i.id}
                        onClick={()=>setActive(i.id)}>
                  <Ic size={16}/>
                  {i.name}
                </button>
              );
            })}
          </div>
        </div>

        <IndustryPanel ind={ind}/>
      </div>
    </section>
  );
};

const IndustryPanel = ({ ind }) => {
  return (
    <div key={ind.id}>
      <div className="relative overflow-hidden rounded-2xl p-7 md:p-10 mb-6 min-h-[220px] flex flex-col justify-end bg-[#0D1B2A] text-white">
        <IndustryScene sceneKey={INDUSTRY_SCENES[ind.id]}/>
        <div className="absolute inset-0 bg-[#0D1B2A]/55" aria-hidden="true"/>
        <div className="relative">
          <h3 className="font-display text-3xl md:text-4xl font-bold leading-tight">{ind.name}</h3>
          <p className="text-white/75 mt-2 max-w-xl">{ind.hook}</p>
        </div>
      </div>

      <div className="grid md:grid-cols-3 gap-6 mb-10">
        <div className="md:col-span-1">
          <h4 className="font-display text-2xl font-bold text-[#0D1B2A] leading-tight">How AI is changing {ind.name}</h4>
        </div>
        <div className="md:col-span-2 space-y-4 text-[#0D1B2A]/80 leading-relaxed">
          {ind.narrative.map((p,i)=>(<p key={i}>{p}</p>))}
        </div>
      </div>

      <div className="border-t border-[#0D1B2A]/10 mb-10"/>

      <div className="mb-12">
        <h4 className="font-display text-2xl font-bold text-[#0D1B2A] mb-6">What this looks like in practice</h4>
        <div className="grid md:grid-cols-3 gap-8">
          {ind.winners.map((w)=>(
            <div key={w.title} className="border-t border-[#0D1B2A]/15 pt-5">
              <h5 className="font-display font-bold text-[#0D1B2A] text-lg leading-snug mb-2">{w.title}</h5>
              <p className="text-sm text-[#0D1B2A]/70 leading-relaxed">{w.body}</p>
            </div>
          ))}
        </div>
      </div>

      <div>
        <h4 className="font-display text-2xl font-bold text-[#0D1B2A] mb-6">Workflows we would automate first</h4>
        <div className="grid md:grid-cols-2 gap-4">
          {ind.workflows.map((w)=>(
            <div key={w.title} className="wf p-5">
              <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-2 md:gap-3 mb-3">
                <h5 className="font-display font-bold text-[#0D1B2A] leading-snug">{w.title}</h5>
                <span className="text-sm font-semibold text-[#04754f] md:text-right md:shrink-0">{w.impact}</span>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div className="rounded-lg border border-[#0D1B2A]/10 bg-[#F8F9FA] p-3">
                  <div className="text-xs font-semibold text-[#0D1B2A]/60 mb-1">Today, manually</div>
                  <p className="text-xs text-[#0D1B2A]/75 leading-relaxed">{w.manual}</p>
                </div>
                <div className="rounded-lg border border-[#3A86FF]/20 bg-[#3A86FF]/5 p-3">
                  <div className="text-xs font-semibold text-[#0a3a8a] mb-1">With Brik agents</div>
                  <p className="text-xs text-[#0D1B2A]/85 leading-relaxed">{w.agent}</p>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ---------- About / Credibility ----------
const About = () => {
  return (
    <section id="about" className="py-20 md:py-28 text-white bg-[#0D1B2A]">
      <div className="max-w-7xl mx-auto px-5 md:px-8">
        <div className="grid md:grid-cols-12 gap-10 items-start">
          <div className="md:col-span-7">
            <h2 className="font-display text-3xl md:text-5xl font-bold leading-tight mb-6">
              Built by engineers.<br/>Based in <span className="text-[#06D6A0]">Seattle</span>.
            </h2>
            <div className="space-y-4 text-white/80 leading-relaxed text-lg max-w-2xl">
              <p>Brik was founded by engineers from Google and Meta who spent years building AI systems used by billions of people. We are based in Seattle, and we started Brik because too many businesses still handle work by hand that existing software could automate in minutes, from dental offices and brokerages to law firms, logistics operators, and machine shops, in every market we serve.</p>
              <p>We build, deploy, and run the AI agents ourselves. <span className="text-white">Each one has to save you time and money, or we have not done our job.</span></p>
            </div>
          </div>

          <div className="md:col-span-5">
            <ul className="space-y-6 border-t border-white/15 pt-6">
              {[
                ["We run what we build","We monitor the agents we deploy, track their results, and handle the on-call work."],
                ["Works with your current software","Agents connect to your ERP, MES, POS, and other systems you already use."],
                ["Accountable on results","Regular check-ins and clear reporting, scheduled around your time zone."],
                ["Measured in results","Every engagement starts with a target for hours or money saved each month. We hit it or we work for free."],
              ].map(([t,b])=>(
                <li key={t} className="flex items-start gap-3">
                  <I.Check size={18} className="tick mt-1 shrink-0"/>
                  <div>
                    <div className="font-display font-semibold">{t}</div>
                    <div className="text-white/65 text-sm leading-relaxed">{b}</div>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>
    </section>
  );
};

// ---------- Frequently Asked Questions ----------
const FAQ_ITEMS = [
  {
    question: "What does the automation audit include?",
    answer: "Over two weeks, we map how work moves through your business, the software your team uses, and the handoffs or repeat tasks that slow things down. You receive an Automation Opportunity Map with priorities, feasibility, and effort—and you keep the report whether or not you hire us to build anything.",
  },
  {
    question: "Do we need to replace our current software?",
    answer: "No. We design agents to work with the software your team already uses wherever the system supports a safe, reliable integration. We confirm access and technical fit during the audit.",
  },
  {
    question: "What kinds of work are a good fit for an AI agent?",
    answer: "High-volume, repetitive workflows with clear inputs and rules are usually a good place to start: document intake, updating records, preparing reports, routing requests, and coordinating handoffs. The audit helps identify which opportunities are practical for your team.",
  },
  {
    question: "Will an agent make decisions without our team?",
    answer: "We agree on each agent’s permissions and escalation rules with you. Routine work can be automated within those boundaries; exceptions and judgment calls go to the people you designate. Your team stays in charge of approvals and consequential decisions.",
  },
  {
    question: "How long does it take to put an agent into production?",
    answer: "The audit takes two weeks. From there, we prioritize a practical roadmap; our process is designed to move from audit to automation over roughly 90 days. Timing depends on the workflow, integrations, and review requirements.",
  },
  {
    question: "How do you measure the results?",
    answer: "We agree on a baseline and track outcomes that matter to the workflow, such as cycle time, staff hours, handoffs, and errors. We review the measured results with you and use them to decide what to improve or automate next.",
  },
];

const Faqs = ({ onNav }) => (
  <section id="faq" aria-labelledby="faq-title" className="py-16 md:py-24 bg-[#F8F9FA]">
    <div className="max-w-7xl mx-auto px-5 md:px-8">
      <div className="grid lg:grid-cols-12 gap-10 lg:gap-16">
        <div className="lg:col-span-4 flex flex-col items-start gap-6">
          <h2 id="faq-title" className="font-display text-3xl md:text-4xl font-bold leading-tight text-[#0D1B2A]">Frequently asked questions</h2>
          <div className="flex flex-wrap gap-3">
            <button type="button" onClick={() => onNav('how')} className="inline-flex min-h-11 items-center gap-2 rounded-lg bg-[#0D1B2A] px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-[#142436] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#3A86FF] focus-visible:ring-offset-2">
              How it works <I.ArrowRight size={16}/>
            </button>
            <button type="button" onClick={() => onNav('audit')} className="inline-flex min-h-11 items-center gap-2 rounded-lg border border-[#0D1B2A]/15 px-4 py-2 text-sm font-medium text-[#0D1B2A] transition-colors hover:bg-[#0D1B2A]/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#3A86FF] focus-visible:ring-offset-2">
              Get your audit <I.ArrowRight size={16}/>
            </button>
          </div>
        </div>
        <div className="lg:col-span-8 border-t border-[#0D1B2A]/15">
          {FAQ_ITEMS.map((item) => (
            <details key={item.question} className="faq-item border-b border-[#0D1B2A]/15">
              <summary className="faq-summary flex min-h-14 cursor-pointer items-center justify-between gap-5 py-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[#3A86FF]">
                <span className="font-sans text-base md:text-lg font-medium text-[#0D1B2A] text-pretty">{item.question}</span>
                <I.ArrowDown size={18} className="faq-chevron shrink-0 text-[#3A86FF]"/>
              </summary>
              <div className="pb-5 pr-8 md:pr-12">
                <p className="max-w-2xl text-sm md:text-base leading-relaxed text-[#0D1B2A]/70">{item.answer}</p>
              </div>
            </details>
          ))}
        </div>
      </div>
    </div>
  </section>
);

// ---------- Audit Form ----------
const INDUSTRY_OPTIONS = [
  'Legal / Accounting / Financial Services',
  'Logistics & Transportation',
  'Home Services & Trades',
  'Manufacturing',
  'Medical & Dental Practice',
  'Aerospace',
  'Real Estate & Property Management',
  'Other',
];

const AuditForm = () => {
  const [form, setForm] = React.useState({
    name:'', email:'', phone:'', company:'', industry:'', employees:'', task:'', referral:'',
  });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);

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

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    if (!form.email.trim()) e.email = 'Required';
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) e.email = 'Enter a valid email';
    if (!form.company.trim()) e.company = 'Required';
    if (!form.industry) e.industry = 'Required';
    if (!form.employees) e.employees = 'Required';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const [submitting, setSubmitting] = React.useState(false);
  const [sendError, setSendError] = React.useState('');

  const submit = async (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setSubmitting(true); setSendError('');
    try {
      const r = await fetch('/api/contact', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({ formType: 'audit', ...form }),
      });
      if (!r.ok) throw new Error((await r.json().catch(()=>({}))).error || 'Failed to send');
      setSubmitted(true);
    } catch (err) {
      setSendError(err.message || 'Something went wrong. Please try again or email contact@getlegaci.com directly.');
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <section id="audit" className="py-20 md:py-28 bg-[#06D6A0]">
        <div className="max-w-3xl mx-auto px-5 md:px-8 text-center text-[#0D1B2A]">
          <div className="inline-flex w-16 h-16 rounded-2xl bg-[#0D1B2A] text-[#06D6A0] items-center justify-center mb-5">
            <I.Check size={32}/>
          </div>
          <h2 className="font-display text-3xl md:text-5xl font-bold mb-4 leading-tight">Got it, {form.name.split(' ')[0] || 'there'}.</h2>
          <p className="text-lg text-[#0D1B2A]/85 leading-relaxed mb-2">Your audit request is in. We&apos;ll reach out to <span className="font-semibold">{form.email}</span> within 24 hours to schedule a short intro call.</p>
          <p className="text-[#0D1B2A]/75">The audit takes two weeks. Talk soon.</p>
          <button onClick={()=>{setSubmitted(false); setForm({name:'',email:'',phone:'',company:'',industry:'',employees:'',task:'',referral:''});}} className="mt-8 text-sm font-semibold underline underline-offset-4">Submit another request</button>
        </div>
      </section>
    );
  }

  return (
    <section id="audit" className="py-20 md:py-28 bg-[#F0F0F0]">
      <div className="max-w-5xl mx-auto px-5 md:px-8">
        <div className="grid md:grid-cols-12 gap-8">
          <div className="md:col-span-5">
            <h2 className="font-display text-3xl md:text-5xl font-bold text-[#0D1B2A] leading-tight mb-5">
              Get your <span className="text-[#3A86FF]">automation audit</span>
            </h2>
            <p className="text-[#0D1B2A]/75 leading-relaxed mb-6">
              Over two weeks, we map how work moves through your business and deliver an Automation Opportunity Map. It shows where AI can save you time and money, with an honest read on feasibility and effort. You keep the report either way.
            </p>
            <ul className="space-y-3 text-sm text-[#0D1B2A]/80">
              {[
                "Detailed map of your highest-leverage workflows",
                "ROI estimate for each automation opportunity",
                "Honest assessment of feasibility and effort",
                "You keep the report, even if you don't hire us",
              ].map((t)=>(
                <li key={t} className="flex items-start gap-2"><I.Check size={16} className="tick mt-0.5 shrink-0"/> {t}</li>
              ))}
            </ul>
          </div>

          <div className="md:col-span-7">
            <form onSubmit={submit} className="card p-6 md:p-8" noValidate>
              <div className="grid sm:grid-cols-2 gap-4">
                <div>
                  <label htmlFor="audit-name" className="block text-sm font-medium text-[#0D1B2A]/80 mb-1.5">Full name *</label>
                  <input id="audit-name" className={`field ${errors.name ? 'field-error' : ''}`} value={form.name} onChange={e=>set('name', e.target.value)} placeholder="Jane Smith"/>
                  {errors.name && <p className="text-xs text-[#E5484D] mt-1">{errors.name}</p>}
                </div>
                <div>
                  <label htmlFor="audit-email" className="block text-sm font-medium text-[#0D1B2A]/80 mb-1.5">Email *</label>
                  <input id="audit-email" className={`field ${errors.email ? 'field-error' : ''}`} value={form.email} onChange={e=>set('email', e.target.value)} placeholder="jane@company.com" type="email"/>
                  {errors.email && <p className="text-xs text-[#E5484D] mt-1">{errors.email}</p>}
                </div>
                <div>
                  <label htmlFor="audit-phone" className="block text-sm font-medium text-[#0D1B2A]/80 mb-1.5">Phone</label>
                  <input id="audit-phone" className="field" value={form.phone} onChange={e=>set('phone', e.target.value)} placeholder="+44 20 7946 0000"/>
                </div>
                <div>
                  <label htmlFor="audit-company" className="block text-sm font-medium text-[#0D1B2A]/80 mb-1.5">Company *</label>
                  <input id="audit-company" className={`field ${errors.company ? 'field-error' : ''}`} value={form.company} onChange={e=>set('company', e.target.value)} placeholder="Acme Manufacturing"/>
                  {errors.company && <p className="text-xs text-[#E5484D] mt-1">{errors.company}</p>}
                </div>
                <div>
                  <label htmlFor="audit-industry" className="block text-sm font-medium text-[#0D1B2A]/80 mb-1.5">Industry *</label>
                  <select id="audit-industry" className={`field ${errors.industry ? 'field-error' : ''}`} value={form.industry} onChange={e=>set('industry', e.target.value)}>
                    <option value="">Select…</option>
                    {INDUSTRY_OPTIONS.map(o=>(<option key={o}>{o}</option>))}
                  </select>
                  {errors.industry && <p className="text-xs text-[#E5484D] mt-1">{errors.industry}</p>}
                </div>
                <div>
                  <label htmlFor="audit-employees" className="block text-sm font-medium text-[#0D1B2A]/80 mb-1.5">Employees *</label>
                  <select id="audit-employees" className={`field ${errors.employees ? 'field-error' : ''}`} value={form.employees} onChange={e=>set('employees', e.target.value)}>
                    <option value="">Select…</option>
                    {['1-10','11-50','51-200','201-500','500+'].map(o=>(<option key={o}>{o}</option>))}
                  </select>
                  {errors.employees && <p className="text-xs text-[#E5484D] mt-1">{errors.employees}</p>}
                </div>
                <div className="sm:col-span-2">
                  <label htmlFor="audit-task" className="block text-sm font-medium text-[#0D1B2A]/80 mb-1.5">What&apos;s the most repetitive task your team does every day?</label>
                  <textarea id="audit-task" className="field min-h-[110px] resize-y" value={form.task} onChange={e=>set('task', e.target.value)} placeholder="e.g., Our team spends 3 hours a day manually entering shipping data into our ERP..."/>
                </div>
                <div className="sm:col-span-2">
                  <label htmlFor="audit-referral" className="block text-sm font-medium text-[#0D1B2A]/80 mb-1.5">How did you hear about us?</label>
                  <select id="audit-referral" className="field" value={form.referral} onChange={e=>set('referral', e.target.value)}>
                    <option value="">Select…</option>
                    {['Google Search','Referral','LinkedIn','Event or conference','Other'].map(o=>(<option key={o}>{o}</option>))}
                  </select>
                </div>
              </div>

              <button type="submit" disabled={submitting} className="btn-green mt-6 w-full px-6 py-4 rounded-xl text-base inline-flex items-center justify-center gap-2 disabled:opacity-60 disabled:cursor-not-allowed">
                {submitting ? 'Sending…' : (<>Request your audit <I.ArrowRight size={18}/></>)}
              </button>
              {sendError && <p className="text-sm text-[#E5484D] mt-3 text-center">{sendError}</p>}
              <p className="text-xs text-[#0D1B2A]/60 mt-3 text-center">We&apos;ll reach out within 24 hours to schedule a short intro call. The audit itself takes two weeks. We use your details only to respond to this request. <a href="/privacy.html" className="underline">Privacy policy</a></p>
            </form>
          </div>
        </div>
      </div>
    </section>
  );
};

// ---------- Contact ----------
const Contact = () => {
  const [form, setForm] = React.useState({name:'', email:'', message:''});
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const set = (k,v) => setForm(f => ({...f, [k]:v}));
  const [submitting, setSubmitting] = React.useState(false);
  const [sendError, setSendError] = React.useState('');
  const submit = async (ev) => {
    ev.preventDefault();
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    if (!form.email.trim()) e.email = 'Required';
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) e.email = 'Enter a valid email';
    if (!form.message.trim()) e.message = 'Required';
    setErrors(e);
    if (Object.keys(e).length !== 0) return;
    setSubmitting(true); setSendError('');
    try {
      const r = await fetch('/api/contact', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({ formType: 'contact', ...form }),
      });
      if (!r.ok) throw new Error((await r.json().catch(()=>({}))).error || 'Failed to send');
      setSent(true);
    } catch (err) {
      setSendError(err.message || 'Something went wrong. Please try again or email contact@getlegaci.com directly.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section id="contact" className="py-20 md:py-28 bg-white">
      <div className="max-w-7xl mx-auto px-5 md:px-8">
        <div className="grid md:grid-cols-2 gap-10">
          <div>
            <h2 className="font-display text-3xl md:text-5xl font-bold text-[#0D1B2A] leading-tight mb-5">Let&apos;s talk.</h2>
            <p className="text-[#0D1B2A]/75 leading-relaxed max-w-md mb-8">
              Ready for the audit, or not sure whether AI fits your operation yet? Send us a note, and an engineer will reply.
            </p>

            {sent ? (
              <div className="card p-6">
                <div className="flex items-center gap-3 mb-2">
                  <span className="text-[#04754f]"><I.Check/></span>
                  <h4 className="font-display font-bold text-lg text-[#0D1B2A]">Message received.</h4>
                </div>
                <p className="text-sm text-[#0D1B2A]/70">We&apos;ll reply to {form.email} shortly.</p>
              </div>
            ) : (
              <form onSubmit={submit} className="card p-6 space-y-4" noValidate>
                <div>
                  <label htmlFor="contact-name" className="block text-sm font-medium text-[#0D1B2A]/80 mb-1.5">Name</label>
                  <input id="contact-name" className={`field ${errors.name?'field-error':''}`} value={form.name} onChange={e=>set('name',e.target.value)}/>
                  {errors.name && <p className="text-xs text-[#E5484D] mt-1">{errors.name}</p>}
                </div>
                <div>
                  <label htmlFor="contact-email" className="block text-sm font-medium text-[#0D1B2A]/80 mb-1.5">Email</label>
                  <input id="contact-email" type="email" className={`field ${errors.email?'field-error':''}`} value={form.email} onChange={e=>set('email',e.target.value)}/>
                  {errors.email && <p className="text-xs text-[#E5484D] mt-1">{errors.email}</p>}
                </div>
                <div>
                  <label htmlFor="contact-message" className="block text-sm font-medium text-[#0D1B2A]/80 mb-1.5">Message</label>
                  <textarea id="contact-message" className={`field min-h-[120px] ${errors.message?'field-error':''}`} value={form.message} onChange={e=>set('message',e.target.value)}/>
                  {errors.message && <p className="text-xs text-[#E5484D] mt-1">{errors.message}</p>}
                </div>
                <button type="submit" disabled={submitting} className="btn-green w-full px-5 py-3 rounded-xl inline-flex items-center justify-center gap-2 disabled:opacity-60 disabled:cursor-not-allowed">{submitting ? 'Sending…' : (<>Send message <I.ArrowRight size={16}/></>)}</button>
                {sendError && <p className="text-sm text-[#E5484D]">{sendError}</p>}
                <p className="text-xs text-[#0D1B2A]/60">We use your details only to respond to your message. <a href="/privacy.html" className="underline">Privacy policy</a></p>
              </form>
            )}
          </div>

          <div>
            <div className="rounded-2xl p-7 md:p-9 text-white bg-[#0D1B2A] self-start">
              <ul className="space-y-6">
                <li className="flex items-start gap-4">
                  <span className="mt-1 text-[#06D6A0]"><I.Mail/></span>
                  <div>
                    <div className="text-white/55 text-sm">Email</div>
                    <a className="font-display text-xl font-semibold hover:text-[#06D6A0] transition" href="mailto:hello@brik.ai">hello@brik.ai</a>
                  </div>
                </li>
                <li className="flex items-start gap-4">
                  <span className="mt-1 text-[#06D6A0]"><I.Phone/></span>
                  <div>
                    <div className="text-white/55 text-sm">Phone</div>
                    <a className="font-display text-xl font-semibold hover:text-[#06D6A0] transition" href="tel:+14258024744">+1 (425) 802-4744</a>
                  </div>
                </li>
                <li className="flex items-start gap-4">
                  <span className="mt-1 text-[#06D6A0]"><I.Pin/></span>
                  <div>
                    <div className="text-white/55 text-sm">Location</div>
                    <div className="font-display text-xl font-semibold">Seattle, Washington</div>
                    <div className="text-white/65 text-sm mt-1">Working with clients in the US, UK, and Europe.</div>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// ---------- Footer ----------
const Footer = ({ onNav }) => {
  const links = [
    { id: 'home', label: 'Home' },
    { id: 'industries', label: 'Industries' },
    { id: 'how', label: 'How It Works' },
    { id: 'audit', label: 'Audit' },
    { id: 'contact', label: 'Contact' },
  ];
  return (
    <footer className="bg-[#0D1B2A] text-white pt-14 pb-8">
      <div className="max-w-7xl mx-auto px-5 md:px-8">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 pb-8 border-b border-white/10">
          <BrikLogo dark size="lg"/>
          <nav className="flex flex-wrap gap-x-6 gap-y-2">
            {links.map(l => (
              <a key={l.id} href={`#${l.id}`} onClick={(e)=>{e.preventDefault(); onNav(l.id);}} className="text-sm text-white/70 hover:text-white transition">{l.label}</a>
            ))}
          </nav>
          <button onClick={()=>onNav('audit')} className="btn-green px-5 py-3 rounded-xl text-sm inline-flex items-center gap-2 self-start md:self-auto">
            Get your automation audit <I.ArrowRight size={16}/>
          </button>
        </div>
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-3 pt-6 text-sm text-white/55">
          <div>© 2026 Brik AI Studio · Seattle, Washington</div>
          <div className="flex gap-5">
            <a href="/privacy.html" className="hover:text-white">Privacy Policy</a>
            <a href="/terms.html" className="hover:text-white">Terms of Service</a>
          </div>
        </div>
      </div>
    </footer>
  );
};

Object.assign(window, { Header, Hero, HERO_VARIANTS, Problem, HowItWorks, Industries, About, AuditForm, Contact, Footer, BrikLogo });
