/* global React */
const { useState: useStateS, useMemo: useMemoS } = React;

// Mock prior responses for realism in sales console
const MOCK_RESPONSES = [
  { id: 1, company: 'Northwind Health',  contact: 'Priya Shah',     status: 'done',    submittedAt: 'May 11, 4:24 PM' },
  { id: 2, company: 'Orbit Logistics',   contact: 'Marc Estevez',   status: 'done',    submittedAt: 'May 10, 9:02 AM' },
  { id: 3, company: 'Helix Bioworks',    contact: 'Sarah Lin',      status: 'pending', submittedAt: 'Sent May 12' },
  { id: 4, company: 'Carbide Aerospace', contact: 'Tom Whitfield',  status: 'pending', submittedAt: 'Sent May 13' },
];

function SalesConsole({ open, onClose, prospect, setProspect, webhookUrl, onSaveWebhook }) {
  const [tab, setTab] = useStateS('prefill');
  const [copied, setCopied] = useStateS(false);
  const [endpointDraft, setEndpointDraft] = useStateS(webhookUrl || '');
  const [endpointSaved, setEndpointSaved] = useStateS(false);
  const [codeCopied, setCodeCopied] = useStateS(false);
  const [scriptPreview, setScriptPreview] = useStateS('');
  const [testState, setTestState] = useStateS('idle'); // idle | testing | ok | fail
  const [testMsg, setTestMsg] = useStateS('');

  React.useEffect(() => { setEndpointDraft(webhookUrl || ''); }, [webhookUrl]);
  React.useEffect(() => {
    // lazy-load the script source so users can see + copy it
    if (tab === 'deploy' && !scriptPreview) {
      fetch('capture-endpoint.gs')
        .then(r => r.ok ? r.text() : '')
        .then(t => setScriptPreview(t || '// (could not load capture-endpoint.gs — open it directly in the project)'))
        .catch(() => setScriptPreview('// (could not load capture-endpoint.gs)'));
    }
  }, [tab, scriptPreview]);

  const link = useMemoS(() => {
    const base = window.location.origin + window.location.pathname;
    const params = new URLSearchParams();
    if (prospect.company) params.set('co', prospect.company);
    if (prospect.contact) params.set('name', prospect.contact);
    if (prospect.role) params.set('role', prospect.role);
    if (prospect.industry) params.set('industry', prospect.industry);
    if (prospect.size) params.set('size', prospect.size);
    if (prospect.hypothesis) params.set('hyp', prospect.hypothesis);
    if (prospect.demoDate) params.set('demo', prospect.demoDate);
    if (prospect.rep) params.set('rep', prospect.rep);
    return base + (params.toString() ? '?' + params.toString() : '');
  }, [prospect]);

  if (!open) return null;

  const upd = (k, v) => setProspect({ ...prospect, [k]: v });

  return (
    <div className="h-sales-drawer" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <aside className="h-sales-panel">
        <div className="h-sales-head">
          <div>
            <div className="h-sales-eyebrow">Sales Console · Internal</div>
            <div className="h-sales-title">Pre-demo briefing</div>
          </div>
          <button className="h-close" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5">
              <path d="M3 3l8 8M11 3l-8 8" />
            </svg>
          </button>
        </div>

        {/* tabs */}
        <div style={{display: 'flex', gap: 4, marginBottom: 8, borderBottom: '1px solid var(--border)'}}>
          {[['prefill', 'Pre-fill & share'], ['responses', 'Responses'], ['deploy', 'Deploy & capture']].map(([k, label]) => (
            <button
              key={k}
              onClick={() => setTab(k)}
              style={{
                background: 'transparent', border: 'none',
                padding: '12px 4px', marginRight: 24,
                fontSize: 12, letterSpacing: '0.1em', textTransform: 'uppercase',
                fontWeight: 500,
                color: tab === k ? 'var(--accent)' : 'var(--fg-muted)',
                borderBottom: tab === k ? '2px solid var(--accent)' : '2px solid transparent',
                marginBottom: -1,
              }}
            >{label}</button>
          ))}
        </div>

        {tab === 'prefill' && (
          <>
            <div className="h-sales-section">
              <h4>Prospect</h4>
              <div className="h-field-row">
                <div className="h-field">
                  <label>Company</label>
                  <input value={prospect.company} onChange={e => upd('company', e.target.value)} placeholder="Acme Industrial" />
                </div>
                <div className="h-field">
                  <label>Contact name</label>
                  <input value={prospect.contact} onChange={e => upd('contact', e.target.value)} placeholder="Jane Cooper" />
                </div>
              </div>
              <div className="h-field-row">
                <div className="h-field">
                  <label>Role</label>
                  <input value={prospect.role} onChange={e => upd('role', e.target.value)} placeholder="VP of Operations" />
                </div>
                <div className="h-field">
                  <label>Industry</label>
                  <input value={prospect.industry} onChange={e => upd('industry', e.target.value)} placeholder="Manufacturing" />
                </div>
              </div>
              <div className="h-field-row">
                <div className="h-field">
                  <label>Company size</label>
                  <select value={prospect.size} onChange={e => upd('size', e.target.value)}>
                    <option value="">Select size…</option>
                    <option>1–50</option>
                    <option>51–200</option>
                    <option>201–1,000</option>
                    <option>1,001–5,000</option>
                    <option>5,000+</option>
                  </select>
                </div>
                <div className="h-field">
                  <label>Demo date</label>
                  <input value={prospect.demoDate} onChange={e => upd('demoDate', e.target.value)} placeholder="May 20 · 2pm PT" />
                </div>
              </div>
            </div>

            <div className="h-sales-section">
              <h4>Sales context</h4>
              <div className="h-field">
                <label>Your hypothesis (private, won't be shown to prospect)</label>
                <input value={prospect.hypothesis} onChange={e => upd('hypothesis', e.target.value)} placeholder="They're drowning in RFPs and AE ramp is 12+ weeks" />
              </div>
              <div className="h-field">
                <label>Sales rep (shown as their contact)</label>
                <input value={prospect.rep} onChange={e => upd('rep', e.target.value)} placeholder="Alex Rivera, Account Executive" />
              </div>
            </div>

            <div className="h-sales-section">
              <h4>Personalized link</h4>
              <div className="h-link-box">
                <code>{link}</code>
                <button onClick={() => {
                  navigator.clipboard?.writeText(link);
                  setCopied(true);
                  setTimeout(() => setCopied(false), 1600);
                }}>{copied ? 'Copied' : 'Copy'}</button>
              </div>
              <p style={{fontSize: 12, color: 'var(--fg-muted)', marginTop: 10, lineHeight: 1.6}}>
                Paste into the calendar invite or follow-up email. The survey will greet them by name,
                show their company throughout, and route answers back to your inbox.
              </p>
            </div>
          </>
        )}

        {tab === 'responses' && (
          <>
            <div className="h-sales-section">
              <h4>This week</h4>
              <div className="h-stat-grid">
                <div className="h-stat">
                  <div className="h-stat-num">12</div>
                  <div className="h-stat-label">Sent</div>
                </div>
                <div className="h-stat">
                  <div className="h-stat-num">8</div>
                  <div className="h-stat-label">Completed</div>
                </div>
                <div className="h-stat">
                  <div className="h-stat-num">67%</div>
                  <div className="h-stat-label">Response rate</div>
                </div>
                <div className="h-stat">
                  <div className="h-stat-num">2:48</div>
                  <div className="h-stat-label">Avg. time to fill</div>
                </div>
              </div>
            </div>

            <div className="h-sales-section">
              <h4>Recent</h4>
              {MOCK_RESPONSES.map(r => (
                <div key={r.id} className="h-resp-card">
                  <div>
                    <div className="h-resp-name">{r.contact} · {r.company}</div>
                    <div className="h-resp-meta">{r.submittedAt}</div>
                  </div>
                  <span className={cn('h-resp-status', r.status === 'done' ? 'is-done' : 'is-pending')}>
                    {r.status === 'done' ? 'Submitted' : 'Awaiting'}
                  </span>
                </div>
              ))}
              <p style={{fontSize: 11, color: 'var(--fg-muted)', marginTop: 16, fontStyle: 'italic'}}>
                Demo data — wire to your CRM to see real responses here.
              </p>
            </div>
          </>
        )}

        {tab === 'deploy' && (
          <>
            <div className="h-sales-section">
              <h4>Status</h4>
              <div style={{display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8}}>
                {webhookUrl ? (
                  <span className="h-status-pill is-live">Endpoint connected</span>
                ) : (
                  <span className="h-status-pill is-empty">Not connected</span>
                )}
                <span style={{fontSize: 12, color: 'var(--fg-muted)'}}>
                  {webhookUrl
                    ? 'New submissions will be captured to your Google Sheet.'
                    : 'Configure an endpoint to capture submissions.'}
                </span>
              </div>
              <div style={{
                padding: '12px 14px', background: '#FFF8E1', border: '1px solid #FFE082',
                borderRadius: 4, fontSize: 12, lineHeight: 1.6, color: '#5C4400'
              }}>
                <b>Important:</b> the endpoint URL you save here only persists in <i>this browser's</i> storage.
                To capture submissions from prospects, put the URL into <code style={{background:'rgba(0,0,0,0.06)',padding:'1px 5px',borderRadius:3}}>config.json</code> in
                the project folder and redeploy. See <code style={{background:'rgba(0,0,0,0.06)',padding:'1px 5px',borderRadius:3}}>FIREBASE-DEPLOY.md</code> step 6.
              </div>
            </div>

            <div className="h-sales-section">
              <h4>1 · Capture endpoint URL</h4>
              <div className="h-field">
                <label>Paste your Apps Script Web app URL</label>
                <input
                  type="url"
                  placeholder="https://script.google.com/macros/s/AKfy.../exec"
                  value={endpointDraft}
                  onChange={e => { setEndpointDraft(e.target.value); setEndpointSaved(false); }}
                />
              </div>
              <div style={{display: 'flex', gap: 8, alignItems: 'center', marginTop: 4}}>
                <button
                  className="h-btn"
                  style={{padding: '8px 16px', fontSize: 11}}
                  onClick={() => {
                    onSaveWebhook(endpointDraft.trim());
                    setEndpointSaved(true);
                    setTimeout(() => setEndpointSaved(false), 2200);
                  }}
                >Save endpoint</button>
                <button
                  className="h-btn h-btn--ghost"
                  style={{padding: '8px 16px', fontSize: 11}}
                  disabled={!endpointDraft.trim() || testState === 'testing'}
                  onClick={async () => {
                    setTestState('testing'); setTestMsg('');
                    try {
                      const fd = new FormData();
                      fd.append('payload', JSON.stringify({
                        submittedAt: new Date().toISOString(),
                        prospect: { company: '[Test] Sales Console', contact: 'Test ping', rep: 'Sales Console' },
                        answers: { selectedPains: [], severities: {}, order: [], tools: [], fix: 'Connectivity test from the Sales Console.', success: '' },
                      }));
                      const res = await fetch(endpointDraft.trim(), { method: 'POST', body: fd });
                      let ok = res.ok;
                      try { const j = await res.json(); ok = ok && (j.ok !== false); } catch {}
                      if (!ok) throw new Error('Endpoint returned an error.');
                      setTestState('ok'); setTestMsg('Pinged — check your Google Sheet for a test row.');
                    } catch (err) {
                      setTestState('fail'); setTestMsg(err.message || 'Network error');
                    }
                  }}
                >{testState === 'testing' ? 'Testing…' : 'Test connection'}</button>
                {endpointSaved && <span style={{fontSize: 11, color: '#006640', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 500}}>Saved</span>}
              </div>
              {testState === 'ok'   && <p style={{fontSize: 12, color: '#006640', marginTop: 10}}>{testMsg}</p>}
              {testState === 'fail' && <p style={{fontSize: 12, color: '#8C0000', marginTop: 10}}>Test failed — {testMsg}</p>}
            </div>

            <div className="h-sales-section">
              <h4>2 · Set up Google Sheet (one-time)</h4>
              <ol className="h-setup-steps">
                <li>Open <b>sheets.google.com</b> and create a blank Sheet named <code>Hive Pre-Demo Briefings</code>.</li>
                <li>In that Sheet: <b>Extensions → Apps Script</b>.</li>
                <li>Replace the placeholder code with the script below. Save.</li>
                <li><b>Deploy → New deployment</b> → Type <code>Web app</code>, Execute as <code>Me</code>, Access <code>Anyone</code>. Click Deploy and authorize.</li>
                <li>Copy the <b>Web app URL</b> shown after deployment → paste it into step 1 above.</li>
              </ol>
            </div>

            <div className="h-sales-section">
              <h4>Apps Script · capture-endpoint.gs</h4>
              <div className="h-code-block">
                <button
                  className="h-code-copy"
                  onClick={() => {
                    navigator.clipboard?.writeText(scriptPreview);
                    setCodeCopied(true);
                    setTimeout(() => setCodeCopied(false), 1600);
                  }}
                >{codeCopied ? 'Copied' : 'Copy'}</button>
                {scriptPreview || 'Loading…'}
              </div>
              <p style={{fontSize: 11, color: 'var(--fg-muted)', marginTop: 10, lineHeight: 1.6}}>
                Want email alerts on every submission? Set <code>NOTIFY_EMAIL</code> at the top of the script, save, then redeploy.
                Full deployment guide lives in <code>DEPLOY.md</code> in this folder.
              </p>
            </div>

            <div className="h-sales-section">
              <h4>3 · Host the survey</h4>
              <p style={{fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.7, margin: '0 0 12px'}}>
                Deploy this folder to <b>Firebase Hosting</b> (Google Cloud's free static-site tier) for a clean
                <code style={{margin: '0 4px'}}>briefing.objectedge.com</code>-style URL — or embed the hosted URL into a
                <b> Google Sites</b> page via <i>Insert → Embed → By URL</i>.
              </p>
              <div className="h-code-block" style={{maxHeight: 110}}>
{`# one-time
npm install -g firebase-tools
firebase login

# in this project folder
firebase init hosting   # public dir: .   single-page: no
firebase deploy`}
              </div>
            </div>
          </>
        )}
      </aside>
    </div>
  );
}

Object.assign(window, { SalesConsole });
