// Enterprise enquiry — sits under the pricing options. A "Talk to us" band that
// opens a category-aware form (different questions per product type) and emails
// the enquiry to info@thevaultstock.com via /api/enterprise-enquiry.

const ENT_CATEGORIES = [
  { key: 'skincare', label: 'Skincare & Beauty', questions: [
    { id: 'How many products / SKUs in your range?', type: 'text', placeholder: 'e.g. 25' },
    { id: 'What do you shoot most?', type: 'select', options: ['Product only', 'On-model', 'Flat-lays & texture', 'A mix'] },
    { id: 'Do you need custom models?', type: 'select', options: ['Yes', 'No', 'Not sure yet'] },
  ]},
  { key: 'apparel', label: 'Apparel & Fashion', questions: [
    { id: 'Roughly how many styles per drop / season?', type: 'text', placeholder: 'e.g. 40' },
    { id: 'Do you need on-model shots?', type: 'select', options: ['Yes, always', 'Sometimes', 'Product only (flat / ghost)'] },
    { id: 'Size / fit range to represent?', type: 'text', placeholder: 'e.g. XS–XXL, inclusive' },
  ]},
  { key: 'jewellery', label: 'Jewellery & Accessories', questions: [
    { id: 'Pieces in a typical collection?', type: 'text', placeholder: 'e.g. 30' },
    { id: 'Do you need macro / close-up detail shots?', type: 'select', options: ['Yes', 'No'] },
    { id: 'On-model, product only, or both?', type: 'select', options: ['On-model', 'Product only', 'Both'] },
  ]},
  { key: 'food', label: 'Food & Beverage', questions: [
    { id: 'Packaged product, styled / plated, or both?', type: 'select', options: ['Packaged product', 'Styled / plated', 'Both'] },
    { id: 'How many products / SKUs?', type: 'text', placeholder: 'e.g. 15' },
    { id: 'Seasonal campaigns or ongoing?', type: 'select', options: ['Seasonal', 'Ongoing', 'Both'] },
  ]},
  { key: 'homeware', label: 'Homeware & Tech', questions: [
    { id: 'How many products / SKUs?', type: 'text', placeholder: 'e.g. 50' },
    { id: 'Do you need room / lifestyle context?', type: 'select', options: ['Yes', 'No', 'Sometimes'] },
    { id: 'Product only or in-scene?', type: 'select', options: ['In-scene', 'Product only', 'Both'] },
  ]},
  { key: 'other', label: 'Something else', questions: [
    { id: 'Tell us about your products and what you make.', type: 'textarea', placeholder: 'A quick description helps us tailor things to you.' },
  ]},
];
const ENT_NEEDS = ['Platform training', 'Extra seats', 'Bulk licensing', 'Custom onboarding'];

function PSEnterprise() {
  const [open, setOpen] = React.useState(false);
  const [cat, setCat] = React.useState('skincare');
  const [answers, setAnswers] = React.useState({});
  const [needs, setNeeds] = React.useState([]);
  const [form, setForm] = React.useState({ name: '', company: '', email: '', teamSize: '', message: '' });
  const [files, setFiles] = React.useState([]); // { id, name, url, uploading, error }
  const [state, setState] = React.useState('idle'); // idle | sending | done | error
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = prev; window.removeEventListener('keydown', onKey); };
  }, [open]);

  const category = ENT_CATEGORIES.find(c => c.key === cat);
  const setField = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toggleNeed = (n) => setNeeds(ns => ns.includes(n) ? ns.filter(x => x !== n) : [...ns, n]);

  const onFiles = async (fileList) => {
    const picked = Array.from(fileList || []).slice(0, 5);
    for (const f of picked) {
      const id = Math.random().toString(36).slice(2);
      setFiles(prev => [...prev, { id, name: f.name, url: '', uploading: true, error: '' }]);
      try {
        const fd = new FormData(); fd.append('file', f);
        const res = await fetch('/api/enterprise-upload', { method: 'POST', body: fd });
        const data = await res.json().catch(() => ({}));
        setFiles(prev => prev.map(x => x.id === id ? { ...x, uploading: false, url: data.url || '', error: res.ok ? '' : (data.error || 'Upload failed') } : x));
      } catch {
        setFiles(prev => prev.map(x => x.id === id ? { ...x, uploading: false, error: 'Upload failed' } : x));
      }
    }
  };
  const removeFile = (id) => setFiles(prev => prev.filter(x => x.id !== id));

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.company || !form.email) { setErr('Please add your name, company and work email.'); return; }
    setState('sending'); setErr('');
    try {
      const res = await fetch('/api/enterprise-enquiry', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          category: cat, categoryLabel: category.label,
          answers, needs, ...form,
          attachments: files.filter(f => f.url).map(f => ({ url: f.url, name: f.name })),
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) { setErr(data.error || 'Could not send. Please email info@thevaultstock.com.'); setState('error'); return; }
      setState('done');
    } catch { setErr('Network error. Please email info@thevaultstock.com.'); setState('error'); }
  };

  const label = { fontFamily: '"La Villa", sans-serif', fontSize: 12, fontWeight: 500, letterSpacing: '0.02em', color: 'var(--fg-2)', marginBottom: 6, display: 'block' };
  const input = { width: '100%', fontFamily: '"La Villa", sans-serif', fontSize: 14, color: 'var(--cocoa)', background: 'var(--cream)', border: '1px solid var(--border-2, rgba(42,36,32,0.18))', borderRadius: 4, padding: '11px 13px', outline: 'none', boxSizing: 'border-box' };

  const field = (q) => (
    <div key={q.id} style={{ marginBottom: 16 }}>
      <label style={label}>{q.id}</label>
      {q.type === 'select' ? (
        <select style={input} value={answers[q.id] || ''} onChange={e => setAnswers(a => ({ ...a, [q.id]: e.target.value }))}>
          <option value="">Select…</option>
          {q.options.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      ) : q.type === 'textarea' ? (
        <textarea style={{ ...input, minHeight: 84, resize: 'vertical' }} placeholder={q.placeholder} value={answers[q.id] || ''} onChange={e => setAnswers(a => ({ ...a, [q.id]: e.target.value }))} />
      ) : (
        <input style={input} type="text" placeholder={q.placeholder} value={answers[q.id] || ''} onChange={e => setAnswers(a => ({ ...a, [q.id]: e.target.value }))} />
      )}
    </div>
  );

  return (
    <section id="enterprise" className="ps-section" data-mobile-pad="true" style={{ background: 'var(--cream)', padding: '56px 48px 80px' }}>
      <div style={{ maxWidth: 1080, margin: '0 auto', border: '1px solid var(--border-2, rgba(42,36,32,0.18))', borderRadius: 8, padding: 'clamp(32px, 5vw, 64px)', background: 'var(--bg-2, #EDE5DA)', display: 'grid', gridTemplateColumns: '1fr auto', gap: 40, alignItems: 'center' }} className="ps-ent-band">
        <div>
          <div className="eyebrow" style={{ marginBottom: 14 }}>
            <span style={{ display: 'inline-block', width: 24, height: 1, background: 'var(--cocoa)', verticalAlign: 'middle', marginRight: 12 }}></span>
            Enterprise
          </div>
          <h2 className="celestial" style={{ fontSize: 'clamp(34px, 4.4vw, 60px)', color: 'var(--cocoa)', margin: '0 0 16px', lineHeight: 1 }}>Need more?<br/>Let&rsquo;s talk.</h2>
          <p style={{ fontFamily: '"La Villa", sans-serif', fontSize: 16, lineHeight: 1.6, color: 'var(--fg-2)', margin: 0, maxWidth: 520 }}>
            For teams that need platform training, extra seats, or bulk licensing across a large catalogue. Tell us a little about your brand and we&rsquo;ll put together the right setup for you.
          </p>
        </div>
        <button onClick={() => { setState('idle'); setOpen(true); }} className="ps-ent-cta" style={{
          fontFamily: '"La Villa", sans-serif', fontSize: 14, fontWeight: 500, letterSpacing: '0.01em',
          color: 'var(--cream)', background: 'var(--cocoa)', border: 'none', padding: '16px 30px', borderRadius: 999,
          cursor: 'pointer', whiteSpace: 'nowrap', transition: 'transform 200ms var(--pe), background 200ms',
        }}
        onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-1px)'; }}
        onMouseLeave={e => { e.currentTarget.style.transform = 'none'; }}>
          Talk to us →
        </button>
      </div>

      <style>{`
        @media (max-width: 760px) {
          .ps-ent-band { grid-template-columns: 1fr !important; gap: 28px !important; }
          .ps-ent-cta { justify-self: start; }
        }
      `}</style>

      {open && (
        <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 300, background: 'rgba(28,20,16,0.55)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '5vh 16px', overflowY: 'auto' }}>
          <div onClick={e => e.stopPropagation()} style={{ width: '100%', maxWidth: 620, background: 'var(--cream)', borderRadius: 10, boxShadow: '0 30px 90px rgba(28,20,16,0.4)', padding: 'clamp(24px, 4vw, 40px)', position: 'relative' }}>
            <button onClick={() => setOpen(false)} aria-label="Close" style={{ position: 'absolute', top: 16, right: 16, background: 'none', border: 'none', color: 'var(--fg-3)', fontSize: 24, lineHeight: 1, cursor: 'pointer' }}>&times;</button>

            {state === 'done' ? (
              <div style={{ textAlign: 'center', padding: '28px 8px' }}>
                <h3 className="celestial" style={{ fontSize: 40, color: 'var(--cocoa)', margin: '0 0 12px' }}>Thank you</h3>
                <p style={{ fontFamily: '"La Villa", sans-serif', fontSize: 16, lineHeight: 1.6, color: 'var(--fg-2)', margin: '0 auto', maxWidth: 380 }}>
                  Your enquiry is on its way to our team. We&rsquo;ll be in touch at <strong style={{ color: 'var(--cocoa)' }}>{form.email}</strong> shortly.
                </p>
                <button onClick={() => setOpen(false)} style={{ marginTop: 28, fontFamily: '"La Villa", sans-serif', fontSize: 13, fontWeight: 500, color: 'var(--cream)', background: 'var(--cocoa)', border: 'none', padding: '13px 28px', borderRadius: 999, cursor: 'pointer' }}>Close</button>
              </div>
            ) : (
              <form onSubmit={submit}>
                <div className="eyebrow" style={{ marginBottom: 8 }}>Creative Studio · Enterprise</div>
                <h3 className="celestial" style={{ fontSize: 'clamp(28px, 4vw, 38px)', color: 'var(--cocoa)', margin: '0 0 22px', lineHeight: 1 }}>Tell us about your brand</h3>

                <label style={label}>What do you make?</label>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 22 }}>
                  {ENT_CATEGORIES.map(c => (
                    <button type="button" key={c.key} onClick={() => { setCat(c.key); setAnswers({}); }} style={{
                      fontFamily: '"La Villa", sans-serif', fontSize: 12.5, cursor: 'pointer', padding: '8px 14px', borderRadius: 999,
                      border: '1px solid ' + (cat === c.key ? 'transparent' : 'var(--border-2, rgba(42,36,32,0.18))'),
                      background: cat === c.key ? 'var(--cocoa)' : 'transparent',
                      color: cat === c.key ? 'var(--cream)' : 'var(--fg-2)',
                    }}>{c.label}</button>
                  ))}
                </div>

                {category.questions.map(field)}

                <div style={{ height: 1, background: 'var(--border-1, rgba(42,36,32,0.10))', margin: '8px 0 22px' }}></div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                  <div style={{ marginBottom: 16 }}><label style={label}>Your name *</label><input style={input} value={form.name} onChange={e => setField('name', e.target.value)} /></div>
                  <div style={{ marginBottom: 16 }}><label style={label}>Company / brand *</label><input style={input} value={form.company} onChange={e => setField('company', e.target.value)} /></div>
                  <div style={{ marginBottom: 16 }}><label style={label}>Work email *</label><input style={input} type="email" value={form.email} onChange={e => setField('email', e.target.value)} /></div>
                  <div style={{ marginBottom: 16 }}><label style={label}>How big is your team?</label><input style={input} placeholder="e.g. 8 people" value={form.teamSize} onChange={e => setField('teamSize', e.target.value)} /></div>
                </div>

                <label style={label}>What are you after?</label>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 18 }}>
                  {ENT_NEEDS.map(n => (
                    <button type="button" key={n} onClick={() => toggleNeed(n)} style={{
                      fontFamily: '"La Villa", sans-serif', fontSize: 12.5, cursor: 'pointer', padding: '8px 14px', borderRadius: 999,
                      border: '1px solid ' + (needs.includes(n) ? 'transparent' : 'var(--border-2, rgba(42,36,32,0.18))'),
                      background: needs.includes(n) ? 'var(--drip-brown, #4A3A30)' : 'transparent',
                      color: needs.includes(n) ? 'var(--cream)' : 'var(--fg-2)',
                    }}>{needs.includes(n) ? '✓ ' : ''}{n}</button>
                  ))}
                </div>

                <div style={{ marginBottom: 18 }}>
                  <label style={label}>Attach a brand deck or product images <span style={{ fontWeight: 400, color: 'var(--fg-2)' }}>(optional)</span></label>
                  <label style={{ ...input, display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer', width: 'auto' }}>
                    <input type="file" multiple accept=".pdf,.ppt,.pptx,.key,.doc,.docx,.zip,image/*" style={{ display: 'none' }} onChange={e => { onFiles(e.target.files); e.target.value = ''; }} />
                    <span>+ Add files</span>
                  </label>
                  {files.length > 0 && (
                    <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 6 }}>
                      {files.map(f => (
                        <div key={f.id} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, fontFamily: '"La Villa", sans-serif' }}>
                          <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: 'var(--cocoa)' }}>{f.name}</span>
                          <span style={{ color: f.error ? '#8C3A2E' : 'var(--fg-2)' }}>{f.uploading ? 'Uploading…' : f.error ? f.error : 'Attached'}</span>
                          <button type="button" onClick={() => removeFile(f.id)} style={{ background: 'none', border: 'none', color: 'var(--fg-2)', cursor: 'pointer', fontSize: 15, lineHeight: 1, padding: 0 }}>&times;</button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
                <div style={{ marginBottom: 18 }}><label style={label}>Anything else?</label><textarea style={{ ...input, minHeight: 76, resize: 'vertical' }} value={form.message} onChange={e => setField('message', e.target.value)} placeholder="Timelines, volumes, anything specific…" /></div>

                {err && <p style={{ fontFamily: '"La Villa", sans-serif', fontSize: 13, color: '#8C3A2E', margin: '0 0 14px' }}>{err}</p>}

                <button type="submit" disabled={state === 'sending'} style={{
                  width: '100%', fontFamily: '"La Villa", sans-serif', fontSize: 14.5, fontWeight: 500, color: 'var(--cream)',
                  background: 'var(--cocoa)', border: 'none', padding: '15px', borderRadius: 999, cursor: state === 'sending' ? 'default' : 'pointer', opacity: state === 'sending' ? 0.6 : 1,
                }}>
                  {state === 'sending' ? 'Sending…' : 'Send enquiry'}
                </button>
                <p style={{ fontFamily: '"La Villa", sans-serif', fontSize: 11.5, color: 'var(--fg-3)', textAlign: 'center', margin: '12px 0 0' }}>Goes straight to our team. We usually reply within 1–2 business days.</p>
              </form>
            )}
          </div>
        </div>
      )}
    </section>
  );
}

Object.assign(window, { PSEnterprise });
