// invodiff-input.jsx — data input state with dual drop zones + vendor selector.

function Icon({ name, size = 16, className = '', style = {} }) {
  const common = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none',
    stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round',
    className, style };
  switch (name) {
    case 'upload': return <svg {...common}><path d="M12 16V4M12 4l-5 5M12 4l5 5M4 20h16"/></svg>;
    case 'file':   return <svg {...common}><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><path d="M14 3v6h6"/></svg>;
    case 'paste':  return <svg {...common}><rect x="8" y="3" width="8" height="4" rx="1"/><path d="M16 5h2a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2"/></svg>;
    case 'arrow':  return <svg {...common}><path d="M5 12h14M13 6l6 6-6 6"/></svg>;
    case 'check':  return <svg {...common}><path d="M5 12l5 5L20 7"/></svg>;
    case 'x':      return <svg {...common}><path d="M6 6l12 12M18 6L6 18"/></svg>;
    case 'flag':   return <svg {...common}><path d="M4 21V4M4 4h12l-2 4 2 4H4"/></svg>;
    case 'spark':  return <svg {...common}><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"/></svg>;
    case 'history':return <svg {...common}><path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/><path d="M12 7v5l3 2"/></svg>;
    case 'chev':   return <svg {...common}><path d="M9 6l6 6-6 6"/></svg>;
    case 'eye':    return <svg {...common}><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>;
    case 'delta':  return <svg {...common}><path d="M12 4 3 20h18z"/></svg>;
    case 'pct':    return <svg {...common}><path d="M19 5 5 19"/><circle cx="7.5" cy="7.5" r="2"/><circle cx="16.5" cy="16.5" r="2"/></svg>;
    case 'rule':   return <svg {...common}><path d="M4 6h16M4 12h10M4 18h16"/></svg>;
    case 'plus':   return <svg {...common}><path d="M12 5v14M5 12h14"/></svg>;
    case 'reset':  return <svg {...common}><path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/></svg>;
    case 'save':   return <svg {...common}><path d="M5 3h11l3 3v15H5z"/><path d="M8 3v6h8V3M8 21v-8h8v8"/></svg>;
    default: return null;
  }
}

// ── DropZone ────────────────────────────────────────────────────────────
function DropZone({ side, value, onChange, label, accent = false }) {
  const [over, setOver]         = React.useState(false);
  const [mode, setMode]         = React.useState(value ? 'loaded' : 'idle');
  const [parsing, setParsing]   = React.useState(false);
  const [parseErr, setParseErr] = React.useState(null);
  const fileInputRef = React.useRef(null);
  const pasteRef     = React.useRef(null);

  React.useEffect(() => {
    if (value && mode !== 'loaded') setMode('loaded');
    if (!value && mode === 'loaded') setMode('idle');
  }, [value]);

  const handleFile = async (file) => {
    if (!file) return;
    setParsing(true);
    setParseErr(null);
    try {
      const invoice = await parseInvoiceFile(file);
      onChange(invoice);
    } catch (e) {
      setParseErr(e.message || 'Could not parse this file.');
    } finally {
      setParsing(false);
    }
  };

  const handlePaste = async () => {
    const text = pasteRef.current?.value || '';
    if (text.trim().length < 10) return;
    setParsing(true);
    setParseErr(null);
    try {
      const invoice = await parseInvoiceText(text);
      onChange(invoice);
    } catch (e) {
      setParseErr(e.message || 'Could not parse pasted text.');
    } finally {
      setParsing(false);
    }
  };

  const onDrop = (e) => {
    e.preventDefault();
    setOver(false);
    handleFile(e.dataTransfer.files[0]);
  };

  const onFileSelect = (e) => {
    handleFile(e.target.files[0]);
    e.target.value = '';
  };

  const clear = () => { onChange(null); setMode('idle'); setParseErr(null); };

  return (
    <div className="dropzone-wrap">
      <div className="dz-hd">
        <div className="dz-tag">
          <span className="dz-letter" style={{ background: side === 'A' ? 'var(--surface-3)' : 'oklch(from var(--accent) l c h / 0.18)', color: side === 'A' ? 'var(--fg-muted)' : 'var(--accent)' }}>{side}</span>
          <div>
            <div className="dz-label">{label}</div>
            <div className="dz-sub">{side === 'A' ? 'Purchase order / baseline / previous invoice' : 'Incoming / new invoice to verify'}</div>
          </div>
        </div>
        {value && (
          <button className="btn btn-ghost btn-sm" onClick={clear}>
            <Icon name="x" size={13}/> Clear
          </button>
        )}
      </div>

      <input
        ref={fileInputRef} type="file"
        accept=".pdf,.xlsx,.xls,.csv,.tsv,.txt,text/*,application/pdf"
        style={{ display: 'none' }} onChange={onFileSelect}
      />

      {!value ? (
        <div
          className={`dropzone ${over ? 'is-over' : ''} ${parsing ? 'is-parsing' : ''}`}
          onDragOver={(e) => { e.preventDefault(); setOver(true); }}
          onDragLeave={() => setOver(false)}
          onDrop={onDrop}
        >
          {parsing ? (
            <>
              <div className="dz-spinner"></div>
              <div className="dz-title">Extracting invoice data…</div>
              <div className="dz-hint">Reading line items and totals</div>
            </>
          ) : (
            <>
              <div className="dz-icon-wrap"><Icon name="upload" size={20} /></div>
              <div className="dz-title">Drop a PDF, Excel, CSV, or text file</div>
              {parseErr && <div className="dz-error">{parseErr}</div>}
              <div className="dz-or">— or —</div>
              <div className="dz-actions">
                <button className="btn btn-sm" onClick={() => fileInputRef.current?.click()}>
                  <Icon name="file" size={13}/> Browse file
                </button>
                <button className="btn btn-sm btn-ghost" onClick={() => { setMode('paste'); setParseErr(null); }}>
                  <Icon name="paste" size={13}/> Paste text
                </button>
                <button className="btn btn-sm btn-ghost" onClick={() => onChange(side === 'A' ? INVOICE_A : INVOICE_B)}>
                  Use sample
                </button>
              </div>
              {mode === 'paste' && (
                <>
                  <textarea
                    ref={pasteRef}
                    className="textarea dz-paste"
                    placeholder={`Paste invoice text for ${label}…`}
                    onKeyDown={(e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) handlePaste(); }}
                  />
                  <button className="btn btn-primary btn-sm" onClick={handlePaste}>
                    <Icon name="spark" size={13}/> Extract data
                  </button>
                </>
              )}
            </>
          )}
        </div>
      ) : (
        <LoadedFileCard invoice={value} side={side} />
      )}
    </div>
  );
}

function LoadedFileCard({ invoice, side }) {
  const total = grandTotal(invoice);
  return (
    <div className="loaded">
      <div className="loaded-hd">
        <div className="loaded-id">
          <Icon name="file" size={14} />
          <span className="mono">{invoice.id}</span>
        </div>
        <span className="status status-ok"><span className="status-dot"/> Parsed</span>
      </div>
      <div className="loaded-rows">
        <div className="lr"><span className="lr-k">Vendor</span><span className="lr-v">{invoice.vendor}</span></div>
        <div className="lr"><span className="lr-k">Date</span><span className="lr-v mono">{invoice.date}</span></div>
        <div className="lr"><span className="lr-k">PO ref</span><span className="lr-v mono">{invoice.poRef}</span></div>
        <div className="lr"><span className="lr-k">Line items</span><span className="lr-v num">{invoice.items.length}</span></div>
        <div className="lr lr-total"><span className="lr-k">Grand total</span><span className="lr-v num">{fmtUSD(total)}</span></div>
      </div>
      <div className="loaded-preview">
        {invoice.items.slice(0, 3).map((it) => (
          <div key={it.sku} className="lp-row">
            <span className="mono" style={{ color: 'var(--fg-dim)' }}>{it.sku}</span>
            <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.desc}</span>
            <span className="num" style={{ color: 'var(--fg-muted)' }}>{fmtUSD(lineTotal(it))}</span>
          </div>
        ))}
        {invoice.items.length > 3 && (
          <div className="lp-more">+{invoice.items.length - 3} more line item{invoice.items.length - 3 === 1 ? '' : 's'}</div>
        )}
      </div>
    </div>
  );
}

// ── InputView ──────────────────────────────────────────────────────────
function InputView({ state, setState, onCompare, vendorRules }) {
  const { invoiceA, invoiceB, vendor } = state;
  const ready = !!invoiceA && !!invoiceB && !!vendor;
  const historyCount = (vendorRules[vendor] || []).length;

  return (
    <div className="input-view">
      <div className="iv-hero">
        <div className="iv-hero-tag mono">01 · NEW COMPARISON</div>
        <h1 className="iv-hero-h">Compare two invoices.</h1>
        <p className="iv-hero-sub">
          Upload or paste extracted text. KCGMatch aligns line items, flags price &amp; quantity drift,
          and applies any historical adjustments you&rsquo;ve saved for this vendor.
        </p>
      </div>

      <div className="iv-vendor card">
        <div className="iv-vendor-inner">
          <div className="iv-vendor-l">
            <div className="label">Vendor name</div>
            <div className="iv-vendor-input">
              <input
                className="input"
                list="vendor-list"
                placeholder="Start typing a vendor name…"
                value={vendor}
                onChange={(e) => setState((s) => ({ ...s, vendor: e.target.value }))}
              />
              <datalist id="vendor-list">
                {SAMPLE_VENDORS.map((v) => <option key={v} value={v} />)}
              </datalist>
            </div>
            <div className="iv-vendor-help">
              Used as the context key for saved corrections &amp; rules.
            </div>
          </div>
          <div className="iv-vendor-r">
            {historyCount > 0 ? (
              <div className="vendor-history vendor-history-on">
                <div className="vh-icon"><Icon name="history" size={16}/></div>
                <div>
                  <div className="vh-title">Applied <span className="num">{historyCount}</span> historical vendor adjustment{historyCount === 1 ? '' : 's'}</div>
                  <div className="vh-sub">Tolerances and ignore-rules from prior reviews will pre-resolve matching variances.</div>
                </div>
              </div>
            ) : (
              <div className="vendor-history">
                <div className="vh-icon vh-icon-dim"><Icon name="history" size={16}/></div>
                <div>
                  <div className="vh-title vh-title-dim">No prior context for this vendor</div>
                  <div className="vh-sub">First-time comparisons rely solely on the two documents below.</div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="iv-drops">
        <DropZone
          side="A"
          label="Invoice A — Baseline"
          value={invoiceA}
          onChange={(v) => setState((s) => ({ ...s, invoiceA: v }))}
        />
        <div className="iv-arrow"><Icon name="arrow" size={18}/></div>
        <DropZone
          side="B"
          accent
          label="Invoice B — Incoming"
          value={invoiceB}
          onChange={(v) => setState((s) => ({ ...s, invoiceB: v }))}
        />
      </div>

      <div className="iv-cta">
        <button className="btn btn-ghost btn-sm" onClick={() => setState({ invoiceA: null, invoiceB: null, vendor: '' })}>
          <Icon name="reset" size={13}/> Reset
        </button>
        <div className="iv-cta-right">
          <span className="iv-cta-hint">
            {!invoiceA && 'Add Invoice A to continue'}
            {invoiceA && !invoiceB && 'Add Invoice B to continue'}
            {invoiceA && invoiceB && !vendor && 'Enter a vendor name to continue'}
            {ready && 'Ready to compare'}
          </span>
          <button className="btn btn-primary btn-lg" disabled={!ready} onClick={onCompare}>
            Run comparison <Icon name="arrow" size={14}/>
          </button>
        </div>
      </div>

      <InputViewStyles />
    </div>
  );
}

const InputViewStyles = () => (
  <style>{`
    .input-view { max-width: 1180px; margin: 0 auto; padding: 56px 28px 80px; }

    .iv-hero { margin-bottom: 36px; max-width: 720px; }
    .iv-hero-tag { font-size: 10.5px; letter-spacing: 0.14em; color: var(--fg-dim); margin-bottom: 14px; }
    .iv-hero-h { font-size: 38px; line-height: 1.08; letter-spacing: -0.025em; margin: 0 0 12px; font-weight: 600; }
    .iv-hero-sub { color: var(--fg-muted); font-size: 15px; line-height: 1.55; margin: 0; max-width: 600px; }

    .iv-vendor { margin-bottom: 24px; padding: 18px 20px; }
    .iv-vendor-inner { display: grid; grid-template-columns: 1fr 1.2fr; gap: 28px; align-items: center; }
    .iv-vendor-l .label { margin-bottom: 8px; }
    .iv-vendor-input { position: relative; }
    .iv-vendor-help { font-size: 12px; color: var(--fg-dim); margin-top: 8px; }

    .vendor-history { display: flex; gap: 12px; align-items: flex-start; padding: 12px 14px; border-radius: var(--r); border: 1px dashed var(--border-strong); background: transparent; }
    .vendor-history-on { background: var(--info-bg); border: 1px solid oklch(from var(--info) l calc(c*.4) h / .35); }
    .vh-icon { width: 32px; height: 32px; border-radius: 8px; background: oklch(from var(--info) l c h / .22); color: var(--info); display: grid; place-items: center; flex-shrink: 0; }
    .vh-icon-dim { background: var(--surface-2); color: var(--fg-dim); }
    .vh-title { font-size: 13px; font-weight: 500; }
    .vh-title .num { color: var(--info); font-weight: 600; }
    .vh-title-dim { color: var(--fg-muted); font-weight: 400; }
    .vh-sub { font-size: 12px; color: var(--fg-dim); margin-top: 2px; line-height: 1.5; }

    .iv-drops { display: grid; grid-template-columns: 1fr 40px 1fr; gap: 18px; align-items: stretch; margin-bottom: 24px; }
    .iv-arrow { display: grid; place-items: center; color: var(--fg-dim); }

    .dropzone-wrap { display: flex; flex-direction: column; min-height: 320px; }
    .dz-hd { display: flex; align-items: center; justify-content: space-between; padding-bottom: 10px; }
    .dz-tag { display: flex; align-items: center; gap: 10px; }
    .dz-letter { width: 26px; height: 26px; border-radius: 6px; display: grid; place-items: center; font-family: "IBM Plex Mono", monospace; font-weight: 600; font-size: 12px; }
    .dz-label { font-size: 13px; font-weight: 500; }
    .dz-sub { font-size: 11.5px; color: var(--fg-dim); margin-top: 1px; }

    .dropzone {
      flex: 1;
      border: 1.5px dashed var(--border-strong);
      border-radius: var(--r-lg);
      padding: 36px 20px;
      background: var(--surface);
      display: flex; flex-direction: column; align-items: center; justify-content: center;
      gap: 12px;
      transition: border-color .15s, background .15s;
    }
    .dropzone.is-over { border-color: var(--accent); background: oklch(from var(--accent) l c h / 0.08); }
    .dz-icon-wrap { width: 44px; height: 44px; border-radius: 50%; background: var(--surface-2); border: 1px solid var(--border); display: grid; place-items: center; color: var(--fg-muted); }
    .dz-title { font-size: 13.5px; font-weight: 500; color: var(--fg); }
    .dz-or { font-size: 11px; color: var(--fg-dim); letter-spacing: 0.08em; text-transform: uppercase; }
    .dz-actions { display: flex; gap: 8px; }
    .dz-paste { margin-top: 12px; width: 100%; min-height: 80px; font-family: "IBM Plex Mono", monospace; font-size: 12px; }
    .dz-hint { font-size: 12px; color: var(--fg-dim); }
    .dz-error { font-size: 12px; color: var(--bad); background: var(--bad-bg); border: 1px solid oklch(from var(--bad) l calc(c*.5) h / .35); border-radius: var(--r); padding: 6px 10px; max-width: 340px; text-align: center; line-height: 1.5; }
    .dropzone.is-parsing { pointer-events: none; opacity: 0.8; }
    .dz-spinner { width: 28px; height: 28px; border-radius: 50%; border: 2.5px solid var(--border); border-top-color: var(--accent); animation: dz-spin .7s linear infinite; }
    @keyframes dz-spin { to { transform: rotate(360deg); } }

    .loaded {
      flex: 1;
      background: var(--surface);
      border: 1px solid var(--border);
      border-radius: var(--r-lg);
      box-shadow: var(--shadow-1);
      padding: 16px 18px;
      display: flex; flex-direction: column; gap: 14px;
    }
    .loaded-hd { display: flex; align-items: center; justify-content: space-between; }
    .loaded-id { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--fg); font-weight: 500; }
    .loaded-id .mono { color: var(--fg-muted); font-size: 12px; }
    .loaded-rows { display: flex; flex-direction: column; gap: 6px; padding-top: 4px; border-top: 1px solid var(--border); padding-top: 12px; }
    .lr { display: flex; justify-content: space-between; align-items: baseline; font-size: 12.5px; }
    .lr-k { color: var(--fg-dim); }
    .lr-v { color: var(--fg); font-weight: 500; }
    .lr-total { padding-top: 8px; margin-top: 4px; border-top: 1px dashed var(--border); }
    .lr-total .lr-v { font-size: 14px; }
    .loaded-preview { background: var(--surface-2); border-radius: var(--r); padding: 10px 12px; display: flex; flex-direction: column; gap: 5px; }
    .lp-row { display: grid; grid-template-columns: 72px 1fr 64px; gap: 12px; font-size: 11.5px; align-items: baseline; }
    .lp-more { font-size: 11px; color: var(--fg-dim); padding-top: 4px; border-top: 1px dashed var(--border); margin-top: 4px; }

    .iv-cta { display: flex; align-items: center; justify-content: space-between; padding: 16px 4px 0; border-top: 1px solid var(--border); margin-top: 8px; }
    .iv-cta-right { display: flex; align-items: center; gap: 14px; }
    .iv-cta-hint { font-size: 12px; color: var(--fg-dim); }

    @media (max-width: 880px) {
      .iv-drops { grid-template-columns: 1fr; }
      .iv-arrow { transform: rotate(90deg); }
      .iv-vendor-inner { grid-template-columns: 1fr; }
    }
  `}</style>
);

Object.assign(window, { Icon, InputView, DropZone });
