const { useState, useEffect } = React;

// SVG flag components — true-to-spec, used in Direct Contact and footer
const FlagUS = ({ size = 28 }) => (
  <svg width={size} height={size * 0.66} viewBox="0 0 60 40" className="rounded-sm border border-token flex-shrink-0 overflow-hidden block">
    <rect width="60" height="40" fill="#fff"/>
    {/* 13 stripes */}
    {Array.from({ length: 7 }).map((_, i) => (
      <rect key={i} x="0" y={i * (40/13) * 2} width="60" height={40/13} fill="#B22234"/>
    ))}
    {/* Canton */}
    <rect width="24" height={40 * 7/13} fill="#3C3B6E"/>
    {/* Stars (simplified — 9 dots) */}
    {Array.from({ length: 9 }).map((_, i) => {
      const col = i % 3;
      const row = Math.floor(i / 3);
      return <circle key={i} cx={4 + col * 8} cy={3 + row * 6} r="1.1" fill="#fff"/>;
    })}
  </svg>
);

const FlagIN = ({ size = 28 }) => (
  <svg width={size} height={size * 0.66} viewBox="0 0 60 40" className="rounded-sm border border-token flex-shrink-0 overflow-hidden block">
    <rect width="60" height="13.33" y="0"     fill="#FF9933"/>
    <rect width="60" height="13.33" y="13.33" fill="#fff"/>
    <rect width="60" height="13.33" y="26.66" fill="#138808"/>
    {/* Ashoka chakra */}
    <g transform="translate(30 20)">
      <circle r="4" fill="none" stroke="#000080" strokeWidth="0.7"/>
      <circle r="0.6" fill="#000080"/>
      {Array.from({ length: 24 }).map((_, i) => (
        <line key={i}
          x1="0" y1="0"
          x2={4 * Math.cos(i * Math.PI / 12)}
          y2={4 * Math.sin(i * Math.PI / 12)}
          stroke="#000080" strokeWidth="0.3"/>
      ))}
    </g>
  </svg>
);

const CTAFooter = () => {
  return (
    <>
      {/* Big CTA */}
      <section id="contact" className="relative py-24 md:py-36 border-t border-token overflow-hidden">
        <div className="absolute inset-0 grid-bg grid-bg-fade pointer-events-none opacity-60"/>
        <div className="absolute -bottom-40 left-1/2 -translate-x-1/2 w-[800px] h-[800px] rounded-full pointer-events-none opacity-[0.10]"
          style={{ background: 'conic-gradient(from 200deg, #D6248C, #A14BCC, #7027A8, #1F2754, #D6248C)', filter: 'blur(80px)' }}
        />
        <div className="relative max-w-[1240px] mx-auto px-6 md:px-10">
          <div className="max-w-3xl reveal">
            <Eyebrow>Start now</Eyebrow>
            <h2 className="display text-[48px] md:text-[80px] leading-[0.98] mt-6">
              Start your AI<br/>
              <span className="brand-gradient-text">transformation.</span>
            </h2>
            <p className="mt-6 text-[18px] md:text-[20px] text-muted max-w-xl leading-relaxed">
              Tell us where the friction is. We'll come back with an AIDD pilot scope, a measurable outcome, and a 6-week plan to ship it.
            </p>
          </div>

          <div className="mt-12 grid lg:grid-cols-12 gap-6 reveal">
            {/* Form */}
            <ContactForm/>

            {/* Side: direct contact */}
            <div className="lg:col-span-5 flex flex-col gap-5">
              <div className="card p-6">
                <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-4">Direct contact</div>

                <a href="tel:+918128867877" className="flex items-center gap-3 group">
                  <FlagIN size={28}/>
                  <div className="flex-1">
                    <div className="text-[11px] font-mono uppercase tracking-[0.14em] text-muted">India</div>
                    <div className="text-[16px] font-medium group-hover:text-brand-magenta transition-colors">+91 8128867877</div>
                  </div>
                </a>

                <div className="hr-token my-4"/>

                <a href="mailto:connect@rocketberry.co" className="flex items-center gap-3 group">
                  <div className="w-[28px] h-[20px] rounded-sm border border-token flex items-center justify-center text-brand-navy flex-shrink-0" style={{background:'var(--surface)'}}>
                    <I.Send size={12}/>
                  </div>
                  <div className="flex-1">
                    <div className="text-[11px] font-mono uppercase tracking-[0.14em] text-muted">Email</div>
                    <div className="text-[16px] font-medium group-hover:text-brand-navy transition-colors">connect@rocketberry.co</div>
                  </div>
                </a>
              </div>
              <ContactOption icon="Bot" title="Talk to an AI engineer" desc="Skip the form — book a 30-minute discovery directly with our solutions team." cta="Pick a time"/>
              <ContactOption icon="Globe" title="Partner with Rocketberry" desc="Reseller, system integrator, or technology alliance — let's talk." cta="Apply"/>
            </div>
          </div>

          {/* Office locations */}
          <div className="mt-20 reveal">
            <div className="flex items-end justify-between mb-8 flex-wrap gap-3">
              <div>
                <Eyebrow>Where we are</Eyebrow>
                <h3 className="display text-[28px] md:text-[36px] mt-3">India HQ. Global delivery.</h3>
              </div>
              <div className="font-mono text-[11px] tracking-[0.18em] uppercase text-muted">1 office</div>
            </div>
            <div className="grid md:grid-cols-3 gap-5">
              <OfficeCard
                country="India — HQ"
                flag="🇮🇳"
                color="#D6248C"
                city="To be confirmed"
                lines={['Registered office address', 'will be displayed here.', 'Rocketberry Pvt. Ltd.']}
              />
              <OfficeCard
                country="Delivery"
                flag="🌐"
                color="#7027A8"
                city="Remote-first"
                lines={['Distributed AIDD team', 'across India, EU, and the US.', 'Time-zone overlap on every project.']}
              />
              <OfficeCard
                country="Hours"
                flag="⏱"
                color="#1F2754"
                city="24 / 5"
                lines={['Mon – Fri', '9:00 – 21:00 IST', 'Weekend on-call for production']}
              />
            </div>
          </div>
        </div>
      </section>

      {/* Footer */}
      <footer className="border-t border-token pt-20 pb-10">
        <div className="max-w-[1240px] mx-auto px-6 md:px-10">
          <div className="grid md:grid-cols-12 gap-10">
            <div className="md:col-span-4">
              <img src="assets/logo.jpeg" alt="Rocketberry" className="h-20 w-auto rounded-lg"/>
              <p className="mt-5 text-[14px] text-muted max-w-xs leading-relaxed">
                AI engineering &amp; solutions firm. Outcome-driven systems built with AI-Driven Development.
              </p>
              <div className="mt-6 space-y-2 text-[13px]">
                <a href="tel:+918128867877" className="flex items-center gap-2 text-muted hover:text-[var(--text)] transition-colors">
                  <FlagIN size={18}/> +91 8128867877
                </a>
                <a href="mailto:connect@rocketberry.co" className="flex items-center gap-2 text-muted hover:text-[var(--text)] transition-colors">
                  <I.Send size={14}/> connect@rocketberry.co
                </a>
              </div>
              <div className="mt-6 flex items-center gap-2 text-[11px] font-mono uppercase tracking-[0.18em] text-muted">
                <SwirlMark size={14}/> AIDD-native
              </div>
            </div>
            <FooterCol title="Solutions" links={['AI Chatbots','Smart Documents','Workflow Automation','HRMS','ERP','CRM + Ops']}/>
            <FooterCol title="Industries" links={['Manufacturing','Healthcare','Retail','Logistics','Hospitality','eCommerce']}/>
            <FooterCol title="Company"    links={['About','Case studies','Blog','Careers','Press','Contact']}/>
            <FooterCol title="Platform"   links={['AIDD framework','Architecture','Security','Compliance','Status','Docs']}/>
          </div>

          <div className="mt-16 pt-8 border-t border-token flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div className="text-[12px] font-mono text-muted">© 2026 Rocketberry Pvt. Ltd. · All rights reserved</div>
            <div className="flex items-center gap-5 text-[12px] text-muted">
              <a href="#" className="hover:text-[var(--text)]">Privacy</a>
              <a href="#" className="hover:text-[var(--text)]">Terms</a>
              <a href="#" className="hover:text-[var(--text)]">DPA</a>
              <a href="#" className="hover:text-[var(--text)]">Security</a>
            </div>
          </div>
        </div>
      </footer>
    </>
  );
};

const ContactForm = () => {
  const [form, setForm] = useState({
    name: '', email: '', company: '', role: '', message: '',
    captcha_answer: '', hp: '',
  });
  const [captcha, setCaptcha] = useState({ id: '', question: 'Loading…', loading: true, error: false });
  const [status, setStatus]   = useState({ state: 'idle', msg: '' }); // idle | sending | success | error
  const isFile = typeof window !== 'undefined' && window.location && window.location.protocol === 'file:';

  const loadCaptcha = async () => {
    setCaptcha(c => ({ ...c, loading: true, error: false }));
    if (isFile) {
      // Demo mode — generate a captcha client-side (server PHP can't run on file://)
      const a = 2 + Math.floor(Math.random() * 8);
      const b = 2 + Math.floor(Math.random() * 8);
      setCaptcha({ id: `demo:${a + b}`, question: `What is ${a} + ${b}?`, loading: false, error: false });
      return;
    }
    try {
      const r = await fetch('api/captcha.php', { cache: 'no-store', credentials: 'same-origin' });
      if (!r.ok) throw new Error('captcha_fetch');
      const j = await r.json();
      if (!j.id) throw new Error('captcha_payload');
      setCaptcha({ id: j.id, question: j.question, loading: false, error: false });
    } catch (e) {
      setCaptcha({ id: '', question: 'Could not load captcha — refresh', loading: false, error: true });
    }
  };

  useEffect(() => { loadCaptcha(); }, []);

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

  const submit = async (e) => {
    e.preventDefault();
    if (status.state === 'sending') return;

    // Client-side validation mirroring the server
    if (!form.name.trim())  return setStatus({ state: 'error', msg: 'Please enter your name.' });
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) return setStatus({ state: 'error', msg: 'Please enter a valid work email.' });
    if (!form.message.trim()) return setStatus({ state: 'error', msg: 'Tell us briefly what you want to automate.' });
    if (!form.captcha_answer.trim()) return setStatus({ state: 'error', msg: 'Please solve the captcha.' });

    setStatus({ state: 'sending', msg: '' });

    if (isFile) {
      // Demo mode — verify captcha locally, then pretend success
      const expected = captcha.id.replace(/^demo:/, '');
      await new Promise(r => setTimeout(r, 600));
      if (parseInt(form.captcha_answer, 10) !== parseInt(expected, 10)) {
        setStatus({ state: 'error', msg: 'Captcha answer is incorrect.' });
        loadCaptcha();
        setForm(f => ({ ...f, captcha_answer: '' }));
        return;
      }
      setStatus({ state: 'success', msg: 'Demo only — running off file://. On the deployed PHP host this would email connect@rocketberry.co.' });
      return;
    }

    try {
      const r = await fetch('api/mail.php', {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name, email: form.email, company: form.company,
          role: form.role, message: form.message,
          captcha_id: captcha.id, captcha_answer: form.captcha_answer,
          hp: form.hp,
        }),
      });
      const j = await r.json().catch(() => ({}));
      if (r.ok && j.ok) {
        setStatus({ state: 'success', msg: 'Thanks — a Rocketberry AI engineer will reach out within one business day.' });
        setForm({ name: '', email: '', company: '', role: '', message: '', captcha_answer: '', hp: '' });
        loadCaptcha();
        return;
      }
      const map = {
        invalid_name:    'Please enter a valid name.',
        invalid_email:   'Please enter a valid email address.',
        invalid_message: 'Please describe what you want to automate.',
        captcha_required:'Please solve the captcha.',
        captcha_invalid: 'Captcha is invalid — refreshing…',
        captcha_expired: 'Captcha expired — refreshing…',
        captcha_wrong:   'Captcha answer is incorrect.',
        too_many_links:  'Please remove most links from your message.',
        rate_limited:    'Too many submissions from this network — please try again later.',
        origin_not_allowed: 'This origin is not authorised to submit.',
        send_failed:     'Email server temporarily unavailable — please try again or call us directly.',
      };
      setStatus({ state: 'error', msg: map[j.error] || 'Something went wrong — please try again.' });
      if (['captcha_invalid', 'captcha_expired', 'captcha_wrong'].includes(j.error)) {
        loadCaptcha();
        setForm(f => ({ ...f, captcha_answer: '' }));
      }
    } catch (err) {
      setStatus({ state: 'error', msg: 'Network error — please try again.' });
    }
  };

  if (status.state === 'success') {
    return (
      <div className="lg:col-span-7 card p-7 md:p-10 flex flex-col items-start gap-4"
           style={{borderColor: '#7027A840', background: 'linear-gradient(180deg, #7027A80A 0%, transparent 50%)'}}>
        <div className="w-12 h-12 rounded-xl flex items-center justify-center"
             style={{background: '#7027A814', color: '#7027A8', border: '1px solid #7027A840'}}>
          <I.Check size={22}/>
        </div>
        <div className="font-mono text-[10px] tracking-[0.18em] uppercase" style={{color: '#7027A8'}}>Message sent</div>
        <h3 className="display text-[28px] leading-tight">We've got your brief.</h3>
        <p className="text-[15px] text-muted leading-relaxed max-w-md">{status.msg}</p>
        <button type="button" onClick={() => setStatus({ state: 'idle', msg: '' })}
                className="btn btn-ghost text-[13px] mt-2">
          Send another <I.Arrow size={13}/>
        </button>
      </div>
    );
  }

  return (
    <form className="lg:col-span-7 card p-7 md:p-8" onSubmit={submit} noValidate>
      <div className="grid sm:grid-cols-2 gap-4">
        <Field label="Full name"   placeholder="Avery Chen"            value={form.name}    onChange={update('name')}    required maxLength={120}/>
        <Field label="Work email"  placeholder="avery@company.com"     value={form.email}   onChange={update('email')}   type="email" required maxLength={200}/>
        <Field label="Company"     placeholder="Northwind Industries"  value={form.company} onChange={update('company')} maxLength={160}/>
        <Field label="Role"        placeholder="VP Operations"         value={form.role}    onChange={update('role')}    maxLength={120}/>
      </div>

      <div className="mt-4">
        <label className="block font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-2">What are you trying to automate?</label>
        <textarea
          rows="4"
          required maxLength={5000}
          value={form.message}
          onChange={update('message')}
          placeholder="e.g., We process 8,000 vendor invoices/month manually across 3 ERPs..."
          className="w-full bg-transparent border border-token rounded-lg px-3.5 py-2.5 text-[14px] focus:border-[var(--text)] outline-none transition-colors resize-none"
        />
      </div>

      {/* Honeypot — hidden from real users, irresistible to bots */}
      <div aria-hidden="true" style={{position: 'absolute', left: '-10000px', top: 'auto', width: 1, height: 1, overflow: 'hidden'}}>
        <label>Website (leave blank)</label>
        <input type="text" name="hp" tabIndex="-1" autoComplete="off" value={form.hp} onChange={update('hp')}/>
      </div>

      {/* Offline captcha row */}
      <div className="mt-5 grid sm:grid-cols-[1fr_auto] gap-3 items-end">
        <div>
          <label className="block font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-2 flex items-center gap-2">
            Security check
            <span className="font-mono text-[9.5px] px-1.5 py-0.5 rounded" style={{background: 'var(--bg)', border: '1px solid var(--border)'}}>
              offline · no tracking
            </span>
          </label>
          <div className="flex items-stretch gap-2">
            <div className="flex-1 px-3.5 py-2.5 rounded-lg border border-token text-[14px] flex items-center"
                 style={{background: 'var(--bg)', fontFamily: 'Geist Mono'}}>
              {captcha.loading ? '…' : captcha.question}
            </div>
            <input
              type="text"
              inputMode="numeric"
              autoComplete="off"
              required
              value={form.captcha_answer}
              onChange={update('captcha_answer')}
              placeholder="="
              className="w-20 bg-transparent border border-token rounded-lg px-3.5 py-2.5 text-[14px] text-center focus:border-[var(--text)] outline-none transition-colors"
              style={{fontFamily: 'Geist Mono'}}
            />
            <button
              type="button"
              onClick={loadCaptcha}
              className="btn btn-ghost text-[12px] px-3"
              aria-label="Refresh captcha"
              title="Refresh captcha"
            >
              <I.Loop size={14}/>
            </button>
          </div>
        </div>
      </div>

      {/* Status / errors */}
      {status.state === 'error' && (
        <div className="mt-4 px-3 py-2 rounded-lg text-[13px]"
             style={{background: '#D6248C10', color: '#A11A6E', border: '1px solid #D6248C40'}}>
          {status.msg}
        </div>
      )}

      <div className="mt-6 flex items-center justify-between flex-wrap gap-3">
        <div className="text-[12px] text-muted">We respond within 1 business day.</div>
        <button
          type="submit"
          disabled={status.state === 'sending'}
          className="btn btn-primary text-[15px] px-5 py-3 disabled:opacity-60 disabled:cursor-not-allowed"
        >
          {status.state === 'sending' ? (
            <>
              <span className="inline-block w-3 h-3 rounded-full border-2 border-white/40 border-t-white animate-spin"/>
              Sending…
            </>
          ) : (
            <>Get free consultation <I.Arrow size={14}/></>
          )}
        </button>
      </div>
    </form>
  );
};

const ContactOption = ({icon, title, desc, cta}) => {
  const IconCmp = I[icon];
  return (
    <a href="#" className="card p-6 group hover:-translate-y-0.5 transition-transform flex items-start gap-4">
      <div className="w-10 h-10 rounded-lg border border-token flex items-center justify-center text-muted flex-shrink-0">
        <IconCmp size={18}/>
      </div>
      <div className="flex-1">
        <div className="text-[15px] font-medium">{title}</div>
        <div className="mt-1 text-[13px] text-muted leading-relaxed">{desc}</div>
        <div className="mt-3 inline-flex items-center gap-1 text-[12px] font-mono uppercase tracking-[0.14em]">
          {cta} <I.ArrowUR size={12}/>
        </div>
      </div>
    </a>
  );
};

const FooterCol = ({title, links}) => (
  <div className="md:col-span-2">
    <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-4">{title}</div>
    <ul className="space-y-2.5">
      {links.map(l => (
        <li key={l}><a href="#" className="text-[13.5px] hover:text-[var(--text)] text-muted transition-colors">{l}</a></li>
      ))}
    </ul>
  </div>
);

const OfficeCard = ({country, flag, color, city, lines}) => (
  <div className="card p-7 relative overflow-hidden group hover:-translate-y-0.5 transition-transform">
    <div className="absolute top-0 left-0 right-0 h-1" style={{background: color, opacity: 0.85}}/>
    <div className="flex items-center justify-between mb-6">
      <div className="flex items-center gap-2">
        <span className="text-[22px] leading-none">{flag}</span>
        <span className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted">{country} office</span>
      </div>
      <div className="w-8 h-8 rounded-lg border border-token flex items-center justify-center" style={{color}}>
        <I.Globe size={14}/>
      </div>
    </div>
    <h4 className="display text-[22px] leading-tight">{city}</h4>
    <div className="mt-4 text-[14px] text-muted leading-relaxed">
      {lines.map((l, i) => <div key={i}>{l}</div>)}
    </div>
  </div>
);

// ── Form field primitive (used by ContactForm) ──
const Field = ({label, placeholder, type='text', value, onChange, required, maxLength}) => (
  <div>
    <label className="block font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-2">{label}</label>
    <input
      type={type}
      placeholder={placeholder}
      value={value || ''}
      onChange={onChange}
      required={required}
      maxLength={maxLength}
      className="w-full bg-transparent border border-token rounded-lg px-3.5 py-2.5 text-[14px] focus:border-[var(--text)] outline-none transition-colors"
    />
  </div>
);

window.CTAFooter = CTAFooter;
