// Inline inquiry form — replaces the dark CTA at the bottom of the Engage section.
// Validates, persists to localStorage, and shows a success state on reload.

const INQUIRY_KEY = 'epochcore.inquiry.v1';

function InquiryForm() {
  const [submitted, setSubmitted] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(INQUIRY_KEY)) || null; }
    catch (e) { return null; }
  });

  const [biz, setBiz] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [team, setTeam] = React.useState('5–25');
  const [channel, setChannel] = React.useState('Web');
  const [q, setQ] = React.useState('');
  const [err, setErr] = React.useState('');

  function send() {
    if (!biz.trim()) { setErr('Business name required.'); return; }
    if (!email.match(/^[^@\s]+@[^@\s]+\.[^@\s]+$/)) { setErr('Looks like that email is incomplete.'); return; }
    if (!q.trim()) { setErr('Add one customer question.'); return; }
    setErr('');
    const record = {
      biz, email, team, channel, q,
      at: new Date().toISOString(),
      ref: 'EC-' + Math.random().toString(36).slice(2, 8).toUpperCase(),
    };
    try { localStorage.setItem(INQUIRY_KEY, JSON.stringify(record)); } catch (e) {}
    setSubmitted(record);
  }

  function reset() {
    try { localStorage.removeItem(INQUIRY_KEY); } catch (e) {}
    setSubmitted(null);
    setBiz(''); setEmail(''); setTeam('5–25'); setChannel('Web'); setQ(''); setErr('');
  }

  if (submitted) return <InquirySuccess record={submitted} onReset={reset}/>;

  const formStyles = {
    wrap: { background: TOKEN.paper, border: `1px solid ${TOKEN.hair}`, position: 'relative' },
    head: {
      padding: '14px 22px', borderBottom: `1px solid ${TOKEN.hair}`,
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      background: '#fff',
    },
    body: { padding: '24px 28px 28px' },
    label: { display: 'block', marginBottom: 8 },
    input: {
      width: '100%', background: 'transparent', border: 'none',
      borderBottom: `1px solid ${TOKEN.hair}`,
      padding: '10px 0 12px',
      fontFamily: '"IBM Plex Sans", system-ui', fontSize: 16,
      color: TOKEN.ink, letterSpacing: -0.2, outline: 'none',
    },
    inputFocus: { borderBottom: `1px solid ${TOKEN.orange}` },
    textarea: {
      width: '100%', minHeight: 84, resize: 'none',
      background: 'transparent', border: `1px solid ${TOKEN.hair}`,
      padding: '12px 14px',
      fontFamily: '"IBM Plex Sans", system-ui', fontSize: 15,
      color: TOKEN.ink, letterSpacing: -0.1, outline: 'none', lineHeight: 1.45,
    },
    chipsRow: { display: 'flex', gap: 6, flexWrap: 'wrap' },
    chip: (active) => ({
      padding: '8px 14px', cursor: 'pointer',
      fontFamily: '"IBM Plex Mono", monospace', fontSize: 11,
      letterSpacing: 0.6, textTransform: 'uppercase',
      background: active ? TOKEN.ink : 'transparent',
      color: active ? TOKEN.paper : TOKEN.inkSoft,
      border: `1px solid ${active ? TOKEN.ink : TOKEN.hair}`,
      transition: 'all .15s ease',
    }),
    row: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24, marginBottom: 22 },
    field: { display: 'flex', flexDirection: 'column' },
  };

  return (
    <div style={formStyles.wrap}>
      <CornerMark where="tl"/><CornerMark where="tr"/><CornerMark where="bl"/><CornerMark where="br"/>

      <div style={formStyles.head}>
        <Mono color={TOKEN.orange} weight={600}>INQUIRY · DRAFT</Mono>
        <Mono color={TOKEN.mute}>REF · PENDING</Mono>
      </div>

      <div style={formStyles.body}>
        <div style={formStyles.row}>
          <div style={formStyles.field}>
            <Mono color={TOKEN.mute} style={formStyles.label}>01 · BUSINESS NAME</Mono>
            <input style={formStyles.input}
              value={biz} onChange={e => setBiz(e.target.value)}
              placeholder="Lake Norman Dental"/>
          </div>
          <div style={formStyles.field}>
            <Mono color={TOKEN.mute} style={formStyles.label}>02 · WORK EMAIL</Mono>
            <input style={formStyles.input}
              value={email} onChange={e => setEmail(e.target.value)}
              placeholder="you@yourbusiness.com" type="email"/>
          </div>
        </div>

        <div style={formStyles.row}>
          <div style={formStyles.field}>
            <Mono color={TOKEN.mute} style={formStyles.label}>03 · TEAM SIZE</Mono>
            <div style={formStyles.chipsRow}>
              {['1–5', '5–25', '25–100', '100+'].map(t => (
                <button key={t} style={formStyles.chip(team === t)} onClick={() => setTeam(t)}>{t}</button>
              ))}
            </div>
          </div>
          <div style={formStyles.field}>
            <Mono color={TOKEN.mute} style={formStyles.label}>04 · PRIMARY CHANNEL</Mono>
            <div style={formStyles.chipsRow}>
              {['Web', 'SMS', 'Email', 'Not sure'].map(c => (
                <button key={c} style={formStyles.chip(channel === c)} onClick={() => setChannel(c)}>{c}</button>
              ))}
            </div>
          </div>
        </div>

        <div style={{ marginBottom: 22 }}>
          <Mono color={TOKEN.mute} style={formStyles.label}>05 · ONE QUESTION TO ANSWER AUTOMATICALLY</Mono>
          <textarea style={formStyles.textarea}
            value={q} onChange={e => setQ(e.target.value)}
            placeholder="e.g. Can I book a cleaning next week, and how much does it cost?"/>
        </div>

        {err && (
          <div style={{
            marginBottom: 14, padding: '10px 14px', background: TOKEN.orangeSoft,
            border: `1px solid ${TOKEN.orange}`,
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <Mono color={TOKEN.orange} weight={600}>ERR</Mono>
            <span style={{ fontSize: 13, color: TOKEN.ink, letterSpacing: -0.1 }}>{err}</span>
          </div>
        )}

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
          <Mono color={TOKEN.mute} style={{ maxWidth: 360, lineHeight: 1.5, textTransform: 'none', letterSpacing: 0.1 }}>
            We respond within 1 business day with a 30-min call slot. Mutual NDA on request before details are shared.
          </Mono>
          <button onClick={send} style={{
            height: 52, padding: '0 28px', border: 'none', cursor: 'pointer',
            background: TOKEN.orange, color: '#fff',
            fontFamily: '"IBM Plex Sans"', fontSize: 15, fontWeight: 500, letterSpacing: -0.1,
            display: 'inline-flex', alignItems: 'center', gap: 10,
            transition: 'background .15s ease',
          }}
            onMouseEnter={e => e.currentTarget.style.background = '#ff5500'}
            onMouseLeave={e => e.currentTarget.style.background = TOKEN.orange}
          >
            Send inquiry
            <span style={{ fontFamily: '"IBM Plex Mono", monospace', fontSize: 14, opacity: 0.85 }}>↗</span>
          </button>
        </div>
      </div>
    </div>
  );
}

function InquirySuccess({ record, onReset }) {
  const when = new Date(record.at);
  const stamp = when.toLocaleString('en-US', {
    month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', hour12: true,
  });
  return (
    <div style={{ background: TOKEN.ink, color: TOKEN.paper, position: 'relative', padding: 0 }}>
      <CornerMark where="tl" color="rgba(250,250,247,0.3)"/>
      <CornerMark where="tr" color="rgba(250,250,247,0.3)"/>
      <CornerMark where="bl" color="rgba(250,250,247,0.3)"/>
      <CornerMark where="br" color="rgba(250,250,247,0.3)"/>

      <div style={{
        padding: '14px 22px', borderBottom: `1px solid rgba(250,250,247,0.12)`,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <Mono color={TOKEN.orange} weight={600}>INQUIRY · QUEUED</Mono>
        <Mono color={TOKEN.paper} style={{ opacity: 0.6 }}>REF · {record.ref}</Mono>
      </div>

      <div style={{ padding: '40px 32px 36px', display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 48 }}>
        <div>
          <div style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            width: 44, height: 44, background: TOKEN.orange, color: '#fff', marginBottom: 24,
          }}>
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
              <path d="M3 10 L8 15 L17 5" stroke="currentColor" strokeWidth="2.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <h3 style={{
            fontFamily: '"IBM Plex Sans"', fontSize: 32, fontWeight: 500,
            letterSpacing: -0.9, lineHeight: 1.1, margin: '0 0 12px', color: TOKEN.paper,
          }}>
            Got it, {record.biz.split(/\s+/)[0]}.<br/>
            We will <em style={{ fontFamily: '"IBM Plex Serif"', fontStyle: 'italic', fontWeight: 400, color: TOKEN.orange }}>email you within one business day.</em>
          </h3>
          <p style={{
            fontSize: 15, lineHeight: 1.55, color: 'rgba(250,250,247,0.65)',
            letterSpacing: -0.1, margin: '0 0 24px', maxWidth: 440,
          }}>
            Reply will go to <span style={{ color: TOKEN.paper, fontWeight: 500 }}>{record.email}</span> from {(typeof window !== 'undefined' && window.EPOCHCORE_CONTACT_EMAIL) || 'john@epochcoreqcs.com'} with a 30-min call slot. If you do not see it, check your spam folder.
          </p>
          <button onClick={onReset} style={{
            background: 'transparent', border: `1px solid rgba(250,250,247,0.2)`,
            color: TOKEN.paper, padding: '12px 18px', cursor: 'pointer',
            fontFamily: '"IBM Plex Mono", monospace', fontSize: 11, letterSpacing: 0.6,
            textTransform: 'uppercase',
          }}>↺ Submit another inquiry</button>
        </div>

        <div style={{ borderLeft: `1px solid rgba(250,250,247,0.12)`, paddingLeft: 32 }}>
          <Mono color={TOKEN.orange} weight={600}>SUMMARY</Mono>
          <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 0 }}>
            <SummaryRow k="Business" v={record.biz}/>
            <SummaryRow k="Email" v={record.email}/>
            <SummaryRow k="Team" v={record.team}/>
            <SummaryRow k="Channel" v={record.channel}/>
            <SummaryRow k="Question" v={record.q} multiline/>
            <SummaryRow k="Queued" v={stamp}/>
          </div>
        </div>
      </div>
    </div>
  );
}

function SummaryRow({ k, v, multiline }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '90px 1fr', gap: 14,
      padding: '10px 0', borderTop: `1px solid rgba(250,250,247,0.08)`,
      alignItems: multiline ? 'flex-start' : 'baseline',
    }}>
      <Mono color="rgba(250,250,247,0.45)" size={10}>{k}</Mono>
      <span style={{
        fontFamily: '"IBM Plex Sans"', fontSize: multiline ? 14 : 14,
        color: TOKEN.paper, letterSpacing: -0.1, lineHeight: 1.5,
      }}>{v}</span>
    </div>
  );
}

Object.assign(window, { InquiryForm });
