// invodiff-vendors.jsx — vendor library: list of vendors with saved context + detail.

function VendorsView({ vendorRules, setVendorRules, onCompareWithVendor }) {
  const vendors = Object.keys(vendorRules).filter((v) => (vendorRules[v] || []).length > 0).sort();
  const [activeVendor, setActiveVendor] = React.useState(vendors[0] || null);

  // Keep active in sync when list shrinks/grows
  React.useEffect(() => {
    if (vendors.length === 0) { setActiveVendor(null); return; }
    if (!activeVendor || !vendors.includes(activeVendor)) setActiveVendor(vendors[0]);
  }, [vendors.join('|')]);

  const removeRule = (vendor, ruleId) => {
    setVendorRules((prev) => {
      const next = { ...prev };
      next[vendor] = (next[vendor] || []).filter((r) => r.id !== ruleId);
      if (next[vendor].length === 0) delete next[vendor];
      return next;
    });
  };

  const clearVendor = (vendor) => {
    setVendorRules((prev) => {
      const next = { ...prev };
      delete next[vendor];
      return next;
    });
  };

  if (vendors.length === 0) {
    return (
      <div className="vv">
        <div className="vv-hero">
          <div className="vv-hero-tag mono">VENDOR CONTEXT LIBRARY</div>
          <h1 className="vv-hero-h">No saved vendor context yet.</h1>
          <p className="vv-hero-sub">
            Approve or reject a comparison with a note and it&rsquo;ll appear here, mapped to that vendor.
            Future comparisons against the same vendor pre-apply these rules automatically.
          </p>
        </div>
        <div className="vv-empty card">
          <div className="vv-empty-icon"><Icon name="rule" size={22}/></div>
          <div className="vv-empty-h">Nothing saved</div>
          <div className="vv-empty-sub">Run a comparison to start building vendor memory.</div>
        </div>
        <VendorsStyles />
      </div>
    );
  }

  const ruleCount = (v) => (vendorRules[v] || []).length;
  const total = Object.values(vendorRules).reduce((s, list) => s + (list || []).length, 0);

  return (
    <div className="vv">
      <div className="vv-hero">
        <div className="vv-hero-tag mono">VENDOR CONTEXT LIBRARY</div>
        <h1 className="vv-hero-h">Saved vendor context.</h1>
        <p className="vv-hero-sub">
          <span className="num">{vendors.length}</span> vendor{vendors.length === 1 ? '' : 's'} ·
          <span className="num">{' '}{total}</span> rule{total === 1 ? '' : 's'} on file.
          These pre-resolve matching variances on every new comparison.
        </p>
      </div>

      <div className="vv-layout">
        {/* Vendor tabs / list */}
        <div className="vv-tabs">
          <div className="vv-tabs-h">
            <span className="label">Vendors</span>
            <span className="num vv-tabs-count">{vendors.length}</span>
          </div>
          <div className="vv-tabs-list">
            {vendors.map((v) => (
              <button
                key={v}
                className={`vv-tab ${activeVendor === v ? 'is-on' : ''}`}
                onClick={() => setActiveVendor(v)}
              >
                <span className="vv-tab-name">{v}</span>
                <span className="vv-tab-count num">{ruleCount(v)}</span>
              </button>
            ))}
          </div>
        </div>

        {/* Active vendor detail */}
        {activeVendor && (
          <VendorDetail
            vendor={activeVendor}
            rules={vendorRules[activeVendor] || []}
            onRemove={(id) => removeRule(activeVendor, id)}
            onClear={() => clearVendor(activeVendor)}
            onCompare={() => onCompareWithVendor(activeVendor)}
          />
        )}
      </div>

      <VendorsStyles />
    </div>
  );
}

function VendorDetail({ vendor, rules, onRemove, onClear, onCompare }) {
  const byKind = {
    ignore: rules.filter((r) => r.kind === 'ignore'),
    tolerance: rules.filter((r) => r.kind === 'tolerance'),
    note: rules.filter((r) => r.kind === 'note'),
  };
  const KIND_META = {
    ignore: { label: 'Ignore rules', desc: 'Variances on these patterns are auto-resolved.', tone: 'bad' },
    tolerance: { label: 'Tolerances', desc: 'Small drifts within bounds are auto-resolved.', tone: 'warn' },
    note: { label: 'Vendor notes', desc: 'Contextual notes referenced during comparison.', tone: 'info' },
  };

  return (
    <div className="vv-detail">
      <div className="vv-detail-hd">
        <div>
          <div className="vv-detail-tag mono">VENDOR</div>
          <div className="vv-detail-name">{vendor}</div>
        </div>
        <div className="vv-detail-actions">
          <button className="btn btn-sm" onClick={onClear}>
            <Icon name="x" size={12}/> Clear context
          </button>
          <button className="btn btn-primary btn-sm" onClick={onCompare}>
            <Icon name="plus" size={13}/> New comparison
          </button>
        </div>
      </div>

      <div className="vv-detail-stats">
        <div className="vv-stat"><div className="vv-stat-v num">{byKind.ignore.length}</div><div className="vv-stat-l">Ignore rules</div></div>
        <div className="vv-stat"><div className="vv-stat-v num">{byKind.tolerance.length}</div><div className="vv-stat-l">Tolerances</div></div>
        <div className="vv-stat"><div className="vv-stat-v num">{byKind.note.length}</div><div className="vv-stat-l">Vendor notes</div></div>
      </div>

      {['ignore', 'tolerance', 'note'].map((kind) => {
        const list = byKind[kind];
        if (list.length === 0) return null;
        const meta = KIND_META[kind];
        return (
          <div key={kind} className="vv-section">
            <div className="vv-section-hd">
              <div className="vv-section-l">
                <span className={`vrp-kind vrp-kind-${kind}`}>{kind}</span>
                <div>
                  <div className="vv-section-h">{meta.label}</div>
                  <div className="vv-section-sub">{meta.desc}</div>
                </div>
              </div>
              <span className="num vv-section-n">{list.length}</span>
            </div>
            <div className="vv-rule-list">
              {list.map((r) => (
                <div key={r.id} className="vv-rule">
                  <div className="vv-rule-l">
                    <span className="mono vv-rule-pat">{r.pattern}</span>
                    <span className="vv-rule-note">{r.note}</span>
                  </div>
                  <div className="vv-rule-r">
                    <span className="vv-rule-date mono">{r.added}</span>
                    <button className="btn btn-ghost btn-sm" onClick={() => onRemove(r.id)} title="Remove rule">
                      <Icon name="x" size={12}/>
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

const VendorsStyles = () => (
  <style>{`
    .vv { max-width: 1180px; margin: 0 auto; padding: 48px 28px 80px; }

    .vv-hero { margin-bottom: 32px; max-width: 720px; }
    .vv-hero-tag { font-size: 10.5px; letter-spacing: 0.14em; color: var(--fg-dim); margin-bottom: 14px; }
    .vv-hero-h { font-size: 34px; line-height: 1.08; letter-spacing: -0.025em; margin: 0 0 12px; font-weight: 600; }
    .vv-hero-sub { color: var(--fg-muted); font-size: 14px; line-height: 1.55; margin: 0; max-width: 620px; }
    .vv-hero-sub .num { color: var(--fg); font-weight: 500; padding: 0 2px; }

    .vv-empty { padding: 56px 32px; display: flex; flex-direction: column; align-items: center; gap: 8px; text-align: center; }
    .vv-empty-icon { width: 48px; height: 48px; border-radius: 50%; background: var(--surface-2); display: grid; place-items: center; color: var(--fg-dim); margin-bottom: 6px; }
    .vv-empty-h { font-size: 15px; font-weight: 500; }
    .vv-empty-sub { font-size: 13px; color: var(--fg-dim); }

    .vv-layout { display: grid; grid-template-columns: 280px 1fr; gap: 20px; align-items: flex-start; }

    .vv-tabs { background: var(--surface); border: 1px solid var(--border); border-radius: var(--r-lg); padding: 12px; box-shadow: var(--shadow-1); position: sticky; top: 70px; }
    .vv-tabs-h { display: flex; justify-content: space-between; align-items: baseline; padding: 4px 8px 10px; border-bottom: 1px solid var(--border); }
    .vv-tabs-count { font-size: 11px; color: var(--fg-dim); }
    .vv-tabs-list { display: flex; flex-direction: column; gap: 2px; padding-top: 8px; }
    .vv-tab {
      appearance: none; background: transparent; color: var(--fg-muted);
      border: 0; padding: 10px 10px; border-radius: var(--r);
      font: inherit; font-size: 13px; text-align: left; cursor: pointer;
      display: flex; align-items: center; justify-content: space-between; gap: 8px;
      transition: background .1s, color .1s;
    }
    .vv-tab:hover { background: var(--surface-2); color: var(--fg); }
    .vv-tab.is-on {
      background: oklch(from var(--accent) l c h / 0.14);
      color: var(--fg); font-weight: 500;
      box-shadow: inset 2px 0 0 var(--accent);
    }
    .vv-tab-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; }
    .vv-tab-count { font-size: 11px; color: var(--fg-dim); background: var(--surface-2); padding: 1px 7px; border-radius: 999px; flex-shrink: 0; }
    .vv-tab.is-on .vv-tab-count { background: var(--bg); color: var(--fg-muted); }

    .vv-detail { background: var(--surface); border: 1px solid var(--border); border-radius: var(--r-lg); padding: 22px 24px; box-shadow: var(--shadow-1); }
    .vv-detail-hd { display: flex; justify-content: space-between; align-items: flex-start; padding-bottom: 18px; border-bottom: 1px solid var(--border); margin-bottom: 18px; }
    .vv-detail-tag { font-size: 10.5px; letter-spacing: 0.12em; color: var(--fg-dim); }
    .vv-detail-name { font-size: 22px; font-weight: 600; letter-spacing: -0.015em; margin-top: 4px; }
    .vv-detail-actions { display: flex; gap: 8px; }

    .vv-detail-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 24px; }
    .vv-stat { background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r); padding: 12px 14px; }
    .vv-stat-v { font-size: 22px; font-weight: 600; letter-spacing: -0.02em; color: var(--fg); }
    .vv-stat-l { font-size: 11.5px; color: var(--fg-dim); margin-top: 2px; letter-spacing: 0.04em; text-transform: uppercase; }

    .vv-section { margin-bottom: 20px; }
    .vv-section:last-child { margin-bottom: 0; }
    .vv-section-hd { display: flex; justify-content: space-between; align-items: flex-start; padding-bottom: 10px; }
    .vv-section-l { display: flex; gap: 12px; align-items: flex-start; }
    .vv-section-l .vrp-kind { margin-top: 4px; }
    .vv-section-h { font-size: 13.5px; font-weight: 500; }
    .vv-section-sub { font-size: 12px; color: var(--fg-dim); margin-top: 2px; }
    .vv-section-n { font-size: 12px; color: var(--fg-dim); }

    .vv-rule-list { display: flex; flex-direction: column; gap: 0; border-top: 1px solid var(--border); }
    .vv-rule { display: flex; justify-content: space-between; gap: 16px; padding: 12px 0; border-bottom: 1px dashed var(--border); align-items: flex-start; }
    .vv-rule:last-child { border-bottom: none; }
    .vv-rule-l { display: flex; flex-direction: column; gap: 4px; flex: 1; min-width: 0; }
    .vv-rule-pat { font-size: 12px; color: var(--fg); background: var(--surface-2); padding: 2px 8px; border-radius: 4px; border: 1px solid var(--border); align-self: flex-start; }
    .vv-rule-note { font-size: 13px; color: var(--fg-muted); line-height: 1.5; }
    .vv-rule-r { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
    .vv-rule-date { font-size: 11px; color: var(--fg-dim); }

    @media (max-width: 860px) {
      .vv-layout { grid-template-columns: 1fr; }
      .vv-tabs { position: static; }
      .vv-tabs-list { flex-direction: row; flex-wrap: wrap; }
      .vv-tab { flex: 0 0 auto; }
    }
  `}</style>
);

Object.assign(window, { VendorsView });
