/* modal.jsx — multi-step discovery booking modal (React) */

const { useState, useEffect, useMemo } = React;

const SERVICE_OPTIONS = [
  { id: 'solutions', t: 'Custom AI Solutions', d: 'Document intelligence, predictive analytics, vision, NLP' },
  { id: 'agents', t: 'AI Agents', d: 'Autonomous agents for support, ops, research, compliance' },
  { id: 'products', t: 'AI Products', d: 'Arabic OCR, doc intelligence, ERPNext extensions' },
  { id: 'strategy', t: 'AI Strategy', d: 'Discovery sprint, ROI assessment, roadmap' },
];

const INDUSTRY_OPTIONS = [
  'Government & Public Sector', 'Banking & Finance', 'Healthcare',
  'Energy, Oil & Gas', 'Logistics & Supply Chain', 'Real Estate & Retail',
  'Telecom', 'Other'
];

const DEPLOY_OPTIONS = [
  { id: 'onprem', t: 'On-premise', d: 'Air-gapped or in our data center' },
  { id: 'cloud', t: 'Cloud (UAE-resident)', d: 'Region-locked, frontier models' },
  { id: 'hybrid', t: 'Hybrid', d: 'Mix of on-prem + cloud' },
  { id: 'unsure', t: 'Not sure yet', d: 'Help me decide during discovery' },
];

const TIMELINE_OPTIONS = [
  { id: 'asap', t: 'Within 1 month', d: 'Active procurement / urgent' },
  { id: 'q', t: 'This quarter', d: 'Budget approved, scoping' },
  { id: 'h', t: 'This half', d: 'Strategy phase' },
  { id: 'explore', t: 'Exploring', d: 'No timeline yet' },
];

function isEmail(v) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v); }

function StepDots({ step, total }) {
  return (
    <div className="steps-bar">
      {Array.from({length: total}).map((_, i) => (
        <span key={i} className={`pip ${i < step ? 'done' : i === step ? 'active' : ''}`} />
      ))}
    </div>
  );
}

function ModalApp({ onClose }) {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    service: '', industry: '', deploy: '', timeline: '',
    name: '', email: '', company: '', role: '', message: ''
  });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);

  const TOTAL = 4;

  // Lock body scroll when open
  useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

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

  const validate = () => {
    const e = {};
    if (step === 0 && !data.service) e.service = 'Please pick one';
    if (step === 1 && !data.industry) e.industry = 'Please pick one';
    if (step === 2) {
      if (!data.deploy) e.deploy = 'Please pick one';
      if (!data.timeline) e.timeline = 'Please pick one';
    }
    if (step === 3) {
      if (!data.name.trim()) e.name = 'Required';
      if (!isEmail(data.email)) e.email = 'Valid email required';
      if (!data.company.trim()) e.company = 'Required';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => {
    if (!validate()) return;
    if (step < TOTAL - 1) setStep(step + 1);
    else submit();
  };
  const back = () => setStep(s => Math.max(0, s - 1));

  const submit = () => {
    // Persist locally — simulating CRM submission
    try {
      const submissions = JSON.parse(localStorage.getItem('aidev_leads') || '[]');
      submissions.push({ ...data, ts: new Date().toISOString() });
      localStorage.setItem('aidev_leads', JSON.stringify(submissions));
    } catch (_) {}
    setSubmitted(true);
  };

  if (submitted) {
    const svc = SERVICE_OPTIONS.find(s => s.id === data.service)?.t || data.service;
    const dep = DEPLOY_OPTIONS.find(s => s.id === data.deploy)?.t || data.deploy;
    const tim = TIMELINE_OPTIONS.find(s => s.id === data.timeline)?.t || data.timeline;
    return (
      <>
        <div className="modal-head">
          <div>
            <h3 id="modalTitle">Request received.</h3>
            <p>One of our solution architects will reach out within one business day.</p>
          </div>
          <button className="modal-close" type="button" aria-label="Close" onClick={onClose}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
          </button>
        </div>
        <div className="modal-body">
          <div className="success-state">
            <div className="check-circle">
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12l4 4L19 7"/></svg>
            </div>
            <h3>Thank you, {data.name.split(' ')[0]}.</h3>
            <p>We've logged your request. Expect a written perspective and a calendar link within one business day to <strong>{data.email}</strong>.</p>
            <div className="sum">
              <div className="row"><span className="k">Service</span><span>{svc}</span></div>
              <div className="row"><span className="k">Industry</span><span>{data.industry}</span></div>
              <div className="row"><span className="k">Deployment</span><span>{dep}</span></div>
              <div className="row"><span className="k">Timeline</span><span>{tim}</span></div>
              <div className="row"><span className="k">Company</span><span>{data.company}</span></div>
              <div className="row"><span className="k">Reference</span><span>BRC-{Math.random().toString(36).slice(2,8).toUpperCase()}</span></div>
            </div>
            <button className="btn btn-ghost" type="button" onClick={onClose}>Close</button>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <div className="modal-head">
        <div>
          <h3 id="modalTitle">Book a Discovery Call</h3>
          <p>30 minutes. A straight answer on what's possible, the cost, and the timeline.</p>
        </div>
        <button className="modal-close" type="button" aria-label="Close" onClick={onClose}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
        </button>
      </div>
      <div className="modal-body">
        <StepDots step={step} total={TOTAL} />

        {step === 0 && (
          <div>
            <div className="step-label">Step 01 / 04</div>
            <div className="step-title">What are you trying to build?</div>
            <div className="choice-grid">
              {SERVICE_OPTIONS.map(o => (
                <button
                  key={o.id}
                  type="button"
                  className={`choice ${data.service === o.id ? 'selected' : ''}`}
                  onClick={() => { set('service', o.id); setErrors({}); }}
                >
                  <div className="ct">{o.t}</div>
                  <div className="cd">{o.d}</div>
                </button>
              ))}
            </div>
            {errors.service && <div style={{color:'#ff5f57', fontFamily:'var(--mono)', fontSize:12, marginTop:10}}>{errors.service}</div>}
          </div>
        )}

        {step === 1 && (
          <div>
            <div className="step-label">Step 02 / 04</div>
            <div className="step-title">Which industry are you in?</div>
            <div className="choice-grid">
              {INDUSTRY_OPTIONS.map(o => (
                <button
                  key={o}
                  type="button"
                  className={`choice ${data.industry === o ? 'selected' : ''}`}
                  onClick={() => { set('industry', o); setErrors({}); }}
                >
                  <div className="ct">{o}</div>
                </button>
              ))}
            </div>
            {errors.industry && <div style={{color:'#ff5f57', fontFamily:'var(--mono)', fontSize:12, marginTop:10}}>{errors.industry}</div>}
          </div>
        )}

        {step === 2 && (
          <div>
            <div className="step-label">Step 03 / 04</div>
            <div className="step-title">Deployment & timeline</div>
            <label style={{fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.1em', color:'var(--fg-mute)', textTransform:'uppercase', display:'block', marginBottom:10}}>Deployment preference</label>
            <div className="choice-grid" style={{marginBottom:18}}>
              {DEPLOY_OPTIONS.map(o => (
                <button key={o.id} type="button" className={`choice ${data.deploy === o.id ? 'selected' : ''}`} onClick={() => { set('deploy', o.id); setErrors({}); }}>
                  <div className="ct">{o.t}</div>
                  <div className="cd">{o.d}</div>
                </button>
              ))}
            </div>
            <label style={{fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.1em', color:'var(--fg-mute)', textTransform:'uppercase', display:'block', marginBottom:10}}>When do you want to start?</label>
            <div className="choice-grid">
              {TIMELINE_OPTIONS.map(o => (
                <button key={o.id} type="button" className={`choice ${data.timeline === o.id ? 'selected' : ''}`} onClick={() => { set('timeline', o.id); setErrors({}); }}>
                  <div className="ct">{o.t}</div>
                  <div className="cd">{o.d}</div>
                </button>
              ))}
            </div>
            {(errors.deploy || errors.timeline) && <div style={{color:'#ff5f57', fontFamily:'var(--mono)', fontSize:12, marginTop:10}}>Please answer both.</div>}
          </div>
        )}

        {step === 3 && (
          <div>
            <div className="step-label">Step 04 / 04</div>
            <div className="step-title">Where do we send the brief?</div>
            <div className={`field ${errors.name ? 'error' : ''}`}>
              <label>Full name<span className="req">*</span></label>
              <input type="text" value={data.name} onChange={e => set('name', e.target.value)} placeholder="Khalid Al Mansouri" />
              <span className="err-msg">{errors.name}</span>
            </div>
            <div className={`field ${errors.email ? 'error' : ''}`}>
              <label>Work email<span className="req">*</span></label>
              <input type="email" value={data.email} onChange={e => set('email', e.target.value)} placeholder="khalid@ministry.gov.ae" />
              <span className="err-msg">{errors.email}</span>
            </div>
            <div className={`field ${errors.company ? 'error' : ''}`}>
              <label>Organization<span className="req">*</span></label>
              <input type="text" value={data.company} onChange={e => set('company', e.target.value)} placeholder="Abu Dhabi Department of …" />
              <span className="err-msg">{errors.company}</span>
            </div>
            <div className="field">
              <label>Role / title</label>
              <input type="text" value={data.role} onChange={e => set('role', e.target.value)} placeholder="CTO, Head of AI, Procurement…" />
            </div>
            <div className="field">
              <label>What problem are you trying to solve?</label>
              <textarea value={data.message} onChange={e => set('message', e.target.value)} placeholder="Optional. A few sentences about the use case, data, and constraints will help us prepare." />
            </div>
          </div>
        )}

        <div className="modal-actions">
          <span className="left">Step {step + 1} of {TOTAL}</span>
          <div style={{display:'flex', gap:10}}>
            {step > 0 && <button className="btn btn-ghost" type="button" onClick={back}>← Back</button>}
            <button className="btn btn-primary" type="button" onClick={next}>
              {step === TOTAL - 1 ? 'Submit Request' : 'Continue'} <span className="btn-arrow">→</span>
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

// Mount + open/close wiring
(function () {
  const back = document.getElementById('modal');
  const root = document.getElementById('modalRoot');
  if (!back || !root) return;
  let reactRoot = null;

  function open() {
    if (!reactRoot) reactRoot = ReactDOM.createRoot(root);
    reactRoot.render(<ModalApp onClose={close} />);
    back.classList.add('open');
    back.setAttribute('aria-hidden', 'false');
  }
  function close() {
    back.classList.remove('open');
    back.setAttribute('aria-hidden', 'true');
    document.body.style.overflow = '';
  }
  // Triggers
  document.querySelectorAll('[data-open-modal]').forEach(b => b.addEventListener('click', (e) => { e.preventDefault(); open(); }));
  // Backdrop click
  back.addEventListener('click', (e) => { if (e.target === back) close(); });
  // Esc
  document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && back.classList.contains('open')) close(); });
})();
