/* global React, ReactDOM */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ─────────────────────────────────────────────
// CONFIG — survey content
// ─────────────────────────────────────────────
const PAIN_AREAS = [
  { id: 'search',     label: 'Finding internal info, docs, contracts',     hint: 'Sales decks, SOWs, past proposals, policies…' },
  { id: 'onboard',    label: 'Onboarding & ramping new hires',             hint: 'Time to first productive week' },
  { id: 'rfp',        label: 'Writing RFP responses & proposals',          hint: 'Pulling content from prior wins' },
  { id: 'support',    label: 'Answering customer or partner questions',    hint: 'Repeating answers that exist somewhere' },
  { id: 'compliance', label: 'Compliance, security & policy lookups',      hint: 'Audits, vendor reviews, DPIAs' },
  { id: 'tribal',     label: 'Tracking down the person who knows',         hint: 'Tribal knowledge & expert dependence' },
  { id: 'docs',       label: 'Keeping documentation current',              hint: 'Wikis that go stale fast' },
  { id: 'meetings',   label: 'Synthesizing meeting notes & decisions',     hint: 'What was decided? By whom? When?' },
];

const TOOL_OPTIONS = [
  'SharePoint', 'Confluence', 'Notion', 'Google Drive',
  'Slack search', 'Microsoft Teams', 'Box / Dropbox',
  'Salesforce', 'Internal wiki', 'Email threads',
  'A homegrown tool', 'ChatGPT / Copilot', 'None — it lives in people\'s heads',
];

const ROLES = [
  'COO / Operations', 'CTO / Engineering', 'Head of AI / Data',
  'CRO / Sales leader', 'Customer Success / Support',
  'HR / People', 'Knowledge Manager', 'Other',
];

// ─────────────────────────────────────────────
// HELPERS
// ─────────────────────────────────────────────
const cn = (...xs) => xs.filter(Boolean).join(' ');

function readUrlPrefill() {
  try {
    const params = new URLSearchParams(window.location.search);
    return {
      company: params.get('co') || '',
      contact: params.get('name') || '',
      role: params.get('role') || '',
      industry: params.get('industry') || '',
      size: params.get('size') || '',
      hypothesis: params.get('hyp') || '',
      demoDate: params.get('demo') || '',
      rep: params.get('rep') || '',
    };
  } catch { return {}; }
}

// arrow glyph
const Arrow = () => (
  <svg className="h-arrow" width="16" height="10" viewBox="0 0 16 10" fill="none" stroke="currentColor" strokeWidth="1.5">
    <path d="M1 5h14M11 1l4 4-4 4" />
  </svg>
);

// ─────────────────────────────────────────────
// REUSABLE: question scaffold
// ─────────────────────────────────────────────
function QPanel({ num, total, eyebrow, title, subtitle, optional, children }) {
  return (
    <div className="h-panel" key={num}>
      <div className="h-eyebrow">
        <span className="h-eyebrow-num">{String(num).padStart(2, '0')}</span>
        {eyebrow || `Question ${num} of ${total}`}
      </div>
      <h2 className="h-question">{title}</h2>
      {subtitle && (
        <p className="h-subq">
          {subtitle}
          {optional && <small>· Optional</small>}
        </p>
      )}
      {children}
    </div>
  );
}

// ─────────────────────────────────────────────
// MULTI-SELECT CHIPS
// ─────────────────────────────────────────────
function ChipGroup({ options, value, onChange, max }) {
  const toggle = (id) => {
    if (value.includes(id)) onChange(value.filter(v => v !== id));
    else if (!max || value.length < max) onChange([...value, id]);
  };
  return (
    <div className="h-chips">
      {options.map((opt, i) => {
        const id = opt.id ?? opt;
        const label = opt.label ?? opt;
        const selected = value.includes(id);
        const key = String.fromCharCode(65 + i);
        return (
          <button
            key={id}
            type="button"
            className={cn('h-chip', selected && 'is-selected')}
            onClick={() => toggle(id)}
          >
            <span className="h-chip-key">{key}</span>
            {label}
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────
// SEVERITY RATING
// ─────────────────────────────────────────────
function SeverityRow({ label, value, onChange }) {
  return (
    <div className={cn('h-sev-row', value && 'is-set')}>
      <div>
        <div className="h-sev-label">{label}</div>
      </div>
      <div>
        <div className="h-sev-pills">
          {[1, 2, 3, 4, 5].map(n => (
            <button
              key={n}
              type="button"
              className={cn('h-sev-pill', value === n && 'is-selected')}
              onClick={() => onChange(value === n ? null : n)}
              aria-label={`Severity ${n}`}
            >{n}</button>
          ))}
        </div>
        <div className="h-sev-scale">
          <span>Minor</span><span>Severe</span>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────
// DRAG-TO-RANK
// ─────────────────────────────────────────────
function RankList({ items, onChange }) {
  const [dragId, setDragId] = useState(null);
  const [targetId, setTargetId] = useState(null);

  const move = (from, to) => {
    if (from === to) return;
    const arr = [...items];
    const [moved] = arr.splice(from, 1);
    arr.splice(to, 0, moved);
    onChange(arr);
  };

  return (
    <div className="h-rank-list">
      {items.map((it, i) => (
        <div
          key={it.id}
          className={cn('h-rank-item', dragId === it.id && 'is-dragging', targetId === it.id && dragId !== it.id && 'is-target')}
          draggable
          onDragStart={(e) => {
            setDragId(it.id);
            e.dataTransfer.effectAllowed = 'move';
          }}
          onDragOver={(e) => { e.preventDefault(); setTargetId(it.id); }}
          onDragLeave={() => setTargetId(prev => prev === it.id ? null : prev)}
          onDrop={(e) => {
            e.preventDefault();
            const from = items.findIndex(x => x.id === dragId);
            const to = items.findIndex(x => x.id === it.id);
            if (from >= 0 && to >= 0) move(from, to);
            setDragId(null); setTargetId(null);
          }}
          onDragEnd={() => { setDragId(null); setTargetId(null); }}
        >
          <div className="h-rank-num">{i + 1}</div>
          <div className="h-rank-label">{it.label}</div>
          <div className="h-rank-grip" aria-hidden="true">
            <span /><span /><span />
          </div>
        </div>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────
// SCREENS
// ─────────────────────────────────────────────
function ScreenWelcome({ prospect, onStart }) {
  const firstName = (prospect.contact || '').split(' ')[0] || 'there';
  const co = prospect.company || 'your team';
  return (
    <div className="h-panel h-welcome">
      <div className="h-welcome-eyebrow">A pre-demo briefing from Object Edge</div>
      <h1>
        Hi {firstName} — let's tailor your <span className="h-accent">Hive</span> demo to {co}.
      </h1>
      <p className="h-welcome-lede">
        Eight short questions. No wrong answers. Your responses go straight to the Object Edge team
        preparing your session, so we spend the live time on what actually matters to {co}.
      </p>

      <div className="h-welcome-meta">
        {prospect.company && (
          <div className="h-welcome-meta-item">
            <span className="h-meta-label">Company</span>
            <span className="h-meta-value">{prospect.company}</span>
          </div>
        )}
        {prospect.demoDate && (
          <div className="h-welcome-meta-item">
            <span className="h-meta-label">Demo</span>
            <span className="h-meta-value">{prospect.demoDate}</span>
          </div>
        )}
        {prospect.rep && (
          <div className="h-welcome-meta-item">
            <span className="h-meta-label">Your contact</span>
            <span className="h-meta-value">{prospect.rep}</span>
          </div>
        )}
      </div>

      <div className="h-welcome-cta">
        <button className="h-btn" onClick={onStart}>
          Begin <Arrow />
        </button>
        <span>Takes about 3 minutes</span>
      </div>
    </div>
  );
}

function ScreenRole({ num, total, value, otherValue, onChange, onOtherChange, onEnter, prospect }) {
  const otherRef = useRef(null);
  useEffect(() => {
    if (value === 'Other') {
      // focus the other text input shortly after it renders
      const t = setTimeout(() => otherRef.current?.focus(), 50);
      return () => clearTimeout(t);
    }
  }, [value]);

  return (
    <QPanel
      num={num} total={total}
      title={<>So we get the framing right — what's your role at <span className="h-q-name">{prospect.company || 'the company'}</span>?</>}
      subtitle="Pick the closest match — there's no perfect category."
    >
      <ChipGroup
        options={ROLES.map(r => ({ id: r, label: r }))}
        value={value ? [value] : []}
        onChange={(arr) => onChange(arr[arr.length - 1] || null)}
        max={1}
      />
      {value === 'Other' && (
        <div className="h-other-input">
          <input
            ref={otherRef}
            type="text"
            placeholder="Type your role…"
            value={otherValue || ''}
            onChange={e => onOtherChange(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); onEnter && onEnter(); } }}
          />
        </div>
      )}
    </QPanel>
  );
}

function ScreenPainSelect({ num, total, value, onChange, customPains, onCustomPainsChange }) {
  const [adding, setAdding] = useState(false);
  const [draft, setDraft] = useState('');
  const inputRef = useRef(null);

  useEffect(() => {
    if (adding) {
      const t = setTimeout(() => inputRef.current?.focus(), 30);
      return () => clearTimeout(t);
    }
  }, [adding]);

  const commitDraft = () => {
    const label = draft.trim();
    if (!label) { setAdding(false); setDraft(''); return; }
    // unique id
    const id = 'c-' + Date.now().toString(36) + '-' + Math.floor(Math.random() * 1000);
    onCustomPainsChange([...customPains, { id, label }]);
    // auto-select
    if (!value.includes(id)) onChange([...value, id]);
    setDraft('');
    setAdding(false);
  };

  const removeCustom = (id) => {
    onCustomPainsChange(customPains.filter(c => c.id !== id));
    if (value.includes(id)) onChange(value.filter(v => v !== id));
  };

  // build combined chip list
  const cannedOptions = PAIN_AREAS;
  const customOptions = customPains;

  const toggle = (id) => {
    if (value.includes(id)) onChange(value.filter(v => v !== id));
    else onChange([...value, id]);
  };

  return (
    <QPanel
      num={num} total={total}
      title="Where does your team lose the most time today?"
      subtitle="Pick from common ones below, or add your own. Three to five is the sweet spot."
    >
      <div className="h-chips">
        {cannedOptions.map((opt, i) => {
          const selected = value.includes(opt.id);
          const key = String.fromCharCode(65 + i);
          return (
            <button
              key={opt.id}
              type="button"
              className={cn('h-chip', selected && 'is-selected')}
              onClick={() => toggle(opt.id)}
            >
              <span className="h-chip-key">{key}</span>
              {opt.label}
            </button>
          );
        })}
        {customOptions.map((opt) => {
          const selected = value.includes(opt.id);
          return (
            <span
              key={opt.id}
              className={cn('h-chip', 'is-custom', selected && 'is-selected')}
            >
              <button
                type="button"
                onClick={() => toggle(opt.id)}
                style={{background: 'transparent', border: 'none', padding: 0, color: 'inherit', font: 'inherit', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 10}}
              >
                <span className="h-chip-key">+</span>
                {opt.label}
              </button>
              <button
                type="button"
                className="h-chip-remove"
                onClick={(e) => { e.stopPropagation(); removeCustom(opt.id); }}
                aria-label="Remove"
                title="Remove"
              >×</button>
            </span>
          );
        })}
        {!adding && (
          <button
            type="button"
            className="h-chip is-add"
            onClick={() => setAdding(true)}
          >
            <span className="h-chip-add-plus">+</span>
            Add your own
          </button>
        )}
      </div>

      {adding && (
        <div className="h-custom-row">
          <input
            ref={inputRef}
            type="text"
            placeholder="e.g. Manually reconciling vendor invoices each Friday…"
            value={draft}
            onChange={e => setDraft(e.target.value)}
            onKeyDown={e => {
              if (e.key === 'Enter')  { e.preventDefault(); commitDraft(); }
              if (e.key === 'Escape') { e.preventDefault(); setAdding(false); setDraft(''); }
            }}
            onBlur={() => { if (!draft.trim()) { setAdding(false); } }}
          />
          <span className="h-custom-hint">Press ↵ to add</span>
        </div>
      )}

      <div className="h-help">
        Selected <b>{value.length}</b> · Recommended <kbd>3</kbd>–<kbd>5</kbd>
      </div>
    </QPanel>
  );
}

function getPainLabel(id, customPains = []) {
  const canned = PAIN_AREAS.find(p => p.id === id);
  if (canned) return canned.label;
  const custom = customPains.find(p => p.id === id);
  return custom ? custom.label : id;
}

function ScreenSeverity({ num, total, selectedPains, severities, onChange, customPains }) {
  if (selectedPains.length === 0) {
    return (
      <QPanel num={num} total={total} title="Nothing to rate yet" subtitle="Head back and pick a few pain areas first.">
        <div />
      </QPanel>
    );
  }
  return (
    <QPanel
      num={num} total={total}
      title="How bad does each one hurt?"
      subtitle="1 = minor annoyance · 5 = costs us real money or deals."
    >
      <div className="h-sev-list">
        {selectedPains.map(id => (
          <SeverityRow
            key={id}
            label={getPainLabel(id, customPains)}
            value={severities[id]}
            onChange={(n) => onChange({ ...severities, [id]: n })}
          />
        ))}
      </div>
    </QPanel>
  );
}

function ScreenRank({ num, total, selectedPains, order, onChange, customPains }) {
  // ensure order matches selectedPains list
  useEffect(() => {
    const filtered = order.filter(id => selectedPains.includes(id));
    const missing = selectedPains.filter(id => !order.includes(id));
    if (filtered.length !== order.length || missing.length) {
      onChange([...filtered, ...missing]);
    }
  }, [selectedPains]); // eslint-disable-line

  const items = order
    .filter(id => selectedPains.includes(id))
    .map(id => ({ id, label: getPainLabel(id, customPains) }));

  return (
    <QPanel
      num={num} total={total}
      title="If you could only fix one this quarter, which goes first?"
      subtitle="Drag to rank from most urgent (top) to least."
    >
      <RankList
        items={items}
        onChange={(arr) => onChange(arr.map(x => x.id))}
      />
    </QPanel>
  );
}

function ScreenTools({ num, total, value, onChange, customTools, onCustomToolsChange }) {
  const [adding, setAdding] = useState(false);
  const [draft, setDraft] = useState('');
  const inputRef = useRef(null);

  useEffect(() => {
    if (adding) {
      const t = setTimeout(() => inputRef.current?.focus(), 30);
      return () => clearTimeout(t);
    }
  }, [adding]);

  const commitDraft = () => {
    const label = draft.trim();
    if (!label) { setAdding(false); setDraft(''); return; }
    // dedupe against canned + existing custom
    const exists = TOOL_OPTIONS.includes(label) || customTools.includes(label);
    if (!exists) onCustomToolsChange([...customTools, label]);
    if (!value.includes(label)) onChange([...value, label]);
    setDraft('');
    setAdding(false);
  };

  const removeCustom = (label) => {
    onCustomToolsChange(customTools.filter(t => t !== label));
    if (value.includes(label)) onChange(value.filter(v => v !== label));
  };

  const toggle = (label) => {
    if (value.includes(label)) onChange(value.filter(v => v !== label));
    else onChange([...value, label]);
  };

  return (
    <QPanel
      num={num} total={total}
      title="Where does this knowledge live today?"
      subtitle="Select every tool people actually open when they're hunting for an answer — or add your own."
    >
      <div className="h-chips">
        {TOOL_OPTIONS.map((label, i) => {
          const selected = value.includes(label);
          const key = String.fromCharCode(65 + i);
          return (
            <button
              key={label}
              type="button"
              className={cn('h-chip', selected && 'is-selected')}
              onClick={() => toggle(label)}
            >
              <span className="h-chip-key">{key}</span>
              {label}
            </button>
          );
        })}
        {customTools.map((label) => {
          const selected = value.includes(label);
          return (
            <span
              key={label}
              className={cn('h-chip', 'is-custom', selected && 'is-selected')}
            >
              <button
                type="button"
                onClick={() => toggle(label)}
                style={{background: 'transparent', border: 'none', padding: 0, color: 'inherit', font: 'inherit', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 10}}
              >
                <span className="h-chip-key">+</span>
                {label}
              </button>
              <button
                type="button"
                className="h-chip-remove"
                onClick={(e) => { e.stopPropagation(); removeCustom(label); }}
                aria-label="Remove"
                title="Remove"
              >×</button>
            </span>
          );
        })}
        {!adding && (
          <button
            type="button"
            className="h-chip is-add"
            onClick={() => setAdding(true)}
          >
            <span className="h-chip-add-plus">+</span>
            Add your own
          </button>
        )}
      </div>

      {adding && (
        <div className="h-custom-row">
          <input
            ref={inputRef}
            type="text"
            placeholder="e.g. Snowflake, Looker, Jira, Zendesk macros…"
            value={draft}
            onChange={e => setDraft(e.target.value)}
            onKeyDown={e => {
              if (e.key === 'Enter')  { e.preventDefault(); commitDraft(); }
              if (e.key === 'Escape') { e.preventDefault(); setAdding(false); setDraft(''); }
            }}
            onBlur={() => { if (!draft.trim()) { setAdding(false); } }}
          />
          <span className="h-custom-hint">Press ↵ to add</span>
        </div>
      )}
    </QPanel>
  );
}

function ScreenFix({ num, total, value, onChange, onEnter }) {
  const ref = useRef(null);
  useEffect(() => { ref.current?.focus(); }, []);
  return (
    <QPanel
      num={num} total={total}
      title="If we fixed one thing before your demo, what would it be?"
      subtitle="Be specific. The one thing that, if it disappeared tomorrow, you'd notice."
      optional
    >
      <textarea
        ref={ref}
        className="h-textarea"
        rows={3}
        placeholder="Type your answer here…"
        value={value}
        onChange={e => onChange(e.target.value)}
        onKeyDown={e => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) onEnter(); }}
      />
      <div className="h-help">
        Press <kbd>Cmd</kbd>+<kbd>Enter</kbd> to continue
      </div>
    </QPanel>
  );
}

function ScreenSuccess({ num, total, value, onChange, onEnter }) {
  const ref = useRef(null);
  useEffect(() => { ref.current?.focus(); }, []);
  return (
    <QPanel
      num={num} total={total}
      title="Six months from now, what does success look like?"
      subtitle="A metric, a moment, a story — whichever is easiest to picture."
      optional
    >
      <textarea
        ref={ref}
        className="h-textarea"
        rows={3}
        placeholder="e.g. New AEs are productive in 2 weeks instead of 8…"
        value={value}
        onChange={e => onChange(e.target.value)}
        onKeyDown={e => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) onEnter(); }}
      />
      <div className="h-help">
        Press <kbd>Cmd</kbd>+<kbd>Enter</kbd> to continue
      </div>
    </QPanel>
  );
}

function ScreenDone({ answers, prospect, onSubmit, submitted, submitState = 'idle', submitError = '', onRestart }) {
  const customPains = answers.customPains || [];
  const topPains = (answers.order || [])
    .filter(id => answers.selectedPains.includes(id))
    .slice(0, 3)
    .map(id => ({ id, label: getPainLabel(id, customPains), severity: answers.severities[id] }));

  return (
    <div className="h-panel h-done">
      <div className="h-done-hero">
        {submitted && (
          <div className="h-done-check">
            <svg width="28" height="28" viewBox="0 0 28 28" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 14l6 6 12-14" />
            </svg>
          </div>
        )}
        <h1>
          {submitted
            ? <>That's it. Thanks, {(prospect.contact || 'friend').split(' ')[0]}.</>
            : <>Ready to send it over?</>}
        </h1>
        <p className="h-done-lede">
          {submitted
            ? <>Your sales team will tailor the demo to the priorities below. See you on {prospect.demoDate || 'the call'}.</>
            : <>A quick recap — make sure this looks right, then submit to your sales contact.</>}
        </p>
      </div>

      <div className="h-recap">
        <div className="h-recap-title">Your priorities</div>

        {answers.role && (
          <div className="h-recap-row">
            <div className="h-recap-q">Role</div>
            <div className="h-recap-a">
              {answers.role === 'Other'
                ? (answers.roleOther || 'Other')
                : answers.role}
            </div>
          </div>
        )}

        <div className="h-recap-row">
          <div className="h-recap-q">Top pain points (ranked)</div>
          <div className="h-recap-a">
            {topPains.length === 0
              ? <span style={{color: 'var(--fg-muted)'}}>No pain areas selected yet.</span>
              : topPains.map((p, i) => (
                  <span key={p.id} className="h-pill">
                    <span className="h-pill-num">#{i + 1}</span>
                    {p.label}
                    {p.severity && <span style={{opacity: 0.7, marginLeft: 8}}>· {p.severity}/5</span>}
                  </span>
                ))}
          </div>
        </div>

        {answers.tools.length > 0 && (
          <div className="h-recap-row">
            <div className="h-recap-q">Tools in use</div>
            <div className="h-recap-a">
              {answers.tools.map(t => <span key={t} className="h-recap-tag">{t}</span>)}
            </div>
          </div>
        )}

        {answers.fix && (
          <div className="h-recap-row">
            <div className="h-recap-q">First thing to fix</div>
            <div className="h-recap-a">"{answers.fix}"</div>
          </div>
        )}

        {answers.success && (
          <div className="h-recap-row">
            <div className="h-recap-q">Success in six months</div>
            <div className="h-recap-a">"{answers.success}"</div>
          </div>
        )}
      </div>

      <div className="h-done-actions">
        {submitted ? (
          <button className="h-btn h-btn--ghost" onClick={onRestart}>Start over</button>
        ) : (
          <>
            <button className="h-btn h-btn--ghost" onClick={onRestart} disabled={submitState === 'submitting'}>Start over</button>
            <button className="h-btn" onClick={onSubmit} disabled={submitState === 'submitting'}>
              {submitState === 'submitting' ? 'Sending…' : 'Submit to sales team'} <Arrow />
            </button>
          </>
        )}
      </div>
      {submitState === 'error' && (
        <div style={{
          marginTop: 18, padding: '12px 16px',
          background: '#FFE6E6', border: '1px solid #FFB3B3',
          borderRadius: 6, color: '#8C0000', fontSize: 13, textAlign: 'center'
        }}>
          Couldn't reach the capture endpoint — {submitError || 'unknown error'}.
          <br /><span style={{opacity: 0.7}}>Ask your sales rep to check the endpoint URL in the Sales Console.</span>
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────
// Expose for app.jsx
// ─────────────────────────────────────────────
Object.assign(window, {
  PAIN_AREAS, TOOL_OPTIONS, ROLES,
  readUrlPrefill, cn, Arrow,
  ScreenWelcome, ScreenRole, ScreenPainSelect, ScreenSeverity,
  ScreenRank, ScreenTools, ScreenFix, ScreenSuccess, ScreenDone,
});
