// invodiff-history.jsx — Price History (tracking sheet) — PLACEHOLDER / PREVIEW.
//
// The upcoming feature: pick one material (e.g. "1 1/8 ACR Piping") and see every
// invoice that ever charged for it, across all jobs and vendors, with the unit
// price over time. It answers "what did Porter charge us for this last year vs
// now?" — a historical companion to the per-job Materials drawdown.
//
// This file is intentionally a non-wired preview: the figures below are SAMPLE
// data so the team can see the shape of the screen. When built for real, the
// watchlist is keyed off the matcher's canonical item identity (itemKeyOf /
// normalizeForMatch) so the same physical part collapses across every vendor's
// renamed SKU, exactly like the Match Audit aliases already do.

// ── Sample tracking data (illustrative only) ──────────────────────────────
const PH_SAMPLE_ITEMS = [
  {
    key: 'acr-1-1-8', desc: '1 1/8" ACR Copper Pipe', vendor: 'Porter Pipe & Supply', uom: 'LF',
    series: [
      { date: 'Mar 2024', invoice: 'INV-44821', job: 'KCG-1042', qty: 240, unit: 4.18 },
      { date: 'Jul 2024', invoice: 'INV-51933', job: 'KCG-1067', qty: 180, unit: 4.42 },
      { date: 'Nov 2024', invoice: 'INV-60877', job: 'KCG-1090', qty: 320, unit: 4.65 },
      { date: 'Apr 2025', invoice: 'INV-71204', job: 'KCG-1131', qty: 200, unit: 5.02 },
      { date: 'Sep 2025', invoice: 'INV-80551', job: 'KCG-1168', qty: 260, unit: 5.38 },
      { date: 'Feb 2026', invoice: 'INV-91020', job: 'KCG-1204', qty: 300, unit: 5.74 },
    ],
  },
  {
    key: 'acr-7-8', desc: '7/8" ACR Copper Pipe', vendor: 'Porter Pipe & Supply', uom: 'LF',
    series: [
      { date: 'Feb 2024', invoice: 'INV-43002', job: 'KCG-1039', qty: 400, unit: 3.05 },
      { date: 'Aug 2024', invoice: 'INV-55410', job: 'KCG-1071', qty: 360, unit: 3.21 },
      { date: 'Mar 2025', invoice: 'INV-69880', job: 'KCG-1122', qty: 280, unit: 3.40 },
      { date: 'Oct 2025', invoice: 'INV-82119', job: 'KCG-1175', qty: 420, unit: 3.58 },
      { date: 'Feb 2026', invoice: 'INV-90744', job: 'KCG-1201', qty: 300, unit: 3.66 },
    ],
  },
  {
    key: 'type-l-3-4', desc: '3/4" Type-L Hard Copper', vendor: 'Ferguson', uom: 'LF',
    series: [
      { date: 'Jan 2024', invoice: 'FE-22107', job: 'KCG-1031', qty: 500, unit: 6.40 },
      { date: 'Jun 2024', invoice: 'FE-29850', job: 'KCG-1058', qty: 380, unit: 6.12 },
      { date: 'Dec 2024', invoice: 'FE-38221', job: 'KCG-1101', qty: 240, unit: 6.55 },
      { date: 'May 2025', invoice: 'FE-46903', job: 'KCG-1140', qty: 300, unit: 6.88 },
      { date: 'Jan 2026', invoice: 'FE-55617', job: 'KCG-1198', qty: 260, unit: 7.10 },
    ],
  },
  {
    key: 'emt-1-2', desc: '1/2" EMT Conduit', vendor: 'Elliott Electric', uom: 'EA',
    series: [
      { date: 'Apr 2024', invoice: 'EL-9920', job: 'KCG-1048', qty: 150, unit: 8.90 },
      { date: 'Nov 2024', invoice: 'EL-12044', job: 'KCG-1093', qty: 200, unit: 8.74 },
      { date: 'Jul 2025', invoice: 'EL-15880', job: 'KCG-1155', qty: 175, unit: 9.05 },
      { date: 'Feb 2026', invoice: 'EL-18402', job: 'KCG-1203', qty: 220, unit: 9.42 },
    ],
  },
];

// Reduce a price series to the headline numbers used by the sheet + watchlist.
function phSummarize(item) {
  const s        = item.series;
  const first    = s[0].unit;
  const latest   = s[s.length - 1].unit;
  const changePct = first > 0 ? ((latest - first) / first) * 100 : 0;
  const lo       = Math.min(...s.map((p) => p.unit));
  const hi       = Math.max(...s.map((p) => p.unit));
  const totalQty = s.reduce((a, p) => a + p.qty, 0);
  return { first, latest, changePct, lo, hi, totalQty, count: s.length };
}

// Tiny inline sparkline from a price series.
function PhSparkline({ series, up, width = 120, height = 32 }) {
  const vals = series.map((p) => p.unit);
  const lo = Math.min(...vals), hi = Math.max(...vals);
  const span = hi - lo || 1;
  const pad = 3;
  const pts = vals.map((v, i) => {
    const x = vals.length === 1 ? width / 2 : (i / (vals.length - 1)) * (width - pad * 2) + pad;
    const y = height - pad - ((v - lo) / span) * (height - pad * 2);
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(' ');
  const stroke = up ? 'var(--bad)' : 'var(--ok)';
  const last = pts.split(' ').pop().split(',');
  return (
    <svg className="ph-spark" width={width} height={height} viewBox={`0 0 ${width} ${height}`} aria-hidden="true">
      <polyline points={pts} fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={last[0]} cy={last[1]} r="2.4" fill={stroke} />
    </svg>
  );
}

function PriceHistoryView() {
  const [query,     setQuery]     = React.useState('');
  const [selectedKey, setSelected] = React.useState(PH_SAMPLE_ITEMS[0].key);

  const filtered = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return PH_SAMPLE_ITEMS;
    return PH_SAMPLE_ITEMS.filter((it) =>
      it.desc.toLowerCase().includes(q) || it.vendor.toLowerCase().includes(q));
  }, [query]);

  const selected = PH_SAMPLE_ITEMS.find((it) => it.key === selectedKey) || filtered[0] || PH_SAMPLE_ITEMS[0];
  const sum = phSummarize(selected);
  const up  = sum.changePct >= 0;

  return (
    <div className="ph-view">
      {/* ── Hero ──────────────────────────────────────────────── */}
      <div className="ph-hd">
        <div>
          <div className="ph-eyebrow">Price tracking</div>
          <h1 className="ph-title">Price History</h1>
          <div className="ph-sub">
            Track what every vendor has charged you for the same material over time — look up
            an item and see each invoice and its unit price, across all jobs.
          </div>
        </div>
        <span className="ph-preview-badge"><Icon name="spark" size={12} /> Preview</span>
      </div>

      {/* ── Preview banner ────────────────────────────────────── */}
      <div className="ph-banner">
        <Icon name="history" size={16} />
        <div>
          <strong>Coming soon.</strong> This is a preview of the price-tracking sheet. The figures
          below are sample data — the live version will build this automatically from your invoice
          history, matching the same part even when a vendor renames it or changes its SKU.
        </div>
      </div>

      {/* ── Search + vendor scope ─────────────────────────────── */}
      <div className="ph-search-row">
        <div className="ph-search-wrap">
          <Icon name="search" size={15} className="ph-search-icon" />
          <input
            className="ph-search-input"
            placeholder='Look up an item — e.g. "1 1/8 ACR Piping"'
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
          {query && (
            <button className="ph-search-clear" onClick={() => setQuery('')} aria-label="Clear search">
              <Icon name="x" size={12} />
            </button>
          )}
        </div>
        <span className="ph-search-note">{filtered.length} tracked item{filtered.length !== 1 ? 's' : ''}</span>
      </div>

      <div className="ph-grid">
        {/* ── Watchlist ──────────────────────────────────────── */}
        <div className="ph-watchlist">
          <div className="ph-wl-hd">Tracked materials</div>
          {filtered.length === 0 ? (
            <div className="ph-wl-empty">No sample items match “{query}”.</div>
          ) : filtered.map((it) => {
            const s = phSummarize(it);
            const itUp = s.changePct >= 0;
            return (
              <button
                key={it.key}
                className={`ph-wl-item${it.key === selectedKey ? ' is-on' : ''}`}
                onClick={() => setSelected(it.key)}
              >
                <div className="ph-wl-main">
                  <span className="ph-wl-desc">{it.desc}</span>
                  <span className="ph-wl-vendor">{it.vendor}</span>
                </div>
                <div className="ph-wl-right">
                  <span className="num ph-wl-price">{fmtUSD(s.latest)}</span>
                  <span className={`ph-wl-chg num ${itUp ? 'is-up' : 'is-down'}`}>
                    {itUp ? '▲' : '▼'} {Math.abs(s.changePct).toFixed(0)}%
                  </span>
                </div>
              </button>
            );
          })}
        </div>

        {/* ── Tracking sheet for the selected item ───────────── */}
        <div className="ph-sheet">
          <div className="ph-sheet-hd">
            <div className="ph-sheet-title">
              <div className="ph-sheet-desc">{selected.desc}</div>
              <div className="ph-sheet-vendor">{selected.vendor} · per {selected.uom}</div>
            </div>
            <PhSparkline series={selected.series} up={up} />
          </div>

          <div className="ph-kpis">
            <div className="ph-kpi">
              <div className="ph-kpi-label">Latest</div>
              <div className="num ph-kpi-val">{fmtUSD(sum.latest)}</div>
            </div>
            <div className="ph-kpi">
              <div className="ph-kpi-label">Since first buy</div>
              <div className={`num ph-kpi-val ${up ? 'is-bad' : 'is-ok'}`}>
                {up ? '+' : ''}{sum.changePct.toFixed(0)}%
              </div>
            </div>
            <div className="ph-kpi">
              <div className="ph-kpi-label">Range</div>
              <div className="num ph-kpi-val ph-kpi-sm">{fmtUSD(sum.lo)}–{fmtUSD(sum.hi)}</div>
            </div>
            <div className="ph-kpi">
              <div className="ph-kpi-label">Invoices</div>
              <div className="num ph-kpi-val">{sum.count}</div>
            </div>
          </div>

          <div className="ph-table-wrap">
            <table className="ph-table">
              <thead>
                <tr>
                  <th>Date</th>
                  <th>Invoice</th>
                  <th>Job</th>
                  <th className="ph-r">Qty</th>
                  <th className="ph-r">Unit price</th>
                  <th className="ph-r">vs first</th>
                </tr>
              </thead>
              <tbody>
                {selected.series.map((p, i) => {
                  const delta = sum.first > 0 ? ((p.unit - sum.first) / sum.first) * 100 : 0;
                  return (
                    <tr key={p.invoice}>
                      <td>{p.date}</td>
                      <td className="mono ph-inv">{p.invoice}</td>
                      <td className="mono ph-job">{p.job}</td>
                      <td className="ph-r num">{p.qty.toLocaleString()} {selected.uom}</td>
                      <td className="ph-r num ph-unit">{fmtUSD(p.unit)}</td>
                      <td className="ph-r num">
                        {i === 0
                          ? <span className="ph-base">baseline</span>
                          : <span className={delta >= 0 ? 'ph-up' : 'ph-down'}>{delta >= 0 ? '+' : ''}{delta.toFixed(1)}%</span>}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          <div className="ph-foot-note">
            <Icon name="rule" size={13} />
            When this ships, every row here will link back to its source invoice and job — and the
            same part will be tracked even after a vendor changes its name or SKU, using the matcher’s
            canonical item identity.
          </div>
        </div>
      </div>

      <PriceHistoryStyles />
    </div>
  );
}

const PriceHistoryStyles = () => (
  <style>{`
    .ph-view { max-width: 1200px; margin: 0 auto; padding: 40px 28px 80px; }

    /* ── Hero ───────────────────────────────────────────────── */
    .ph-hd { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 22px; flex-wrap: wrap; }
    .ph-eyebrow { font-family: "IBM Plex Mono", ui-monospace, monospace; font-size: 11px; font-weight: 600; letter-spacing: 0.1em; text-transform: uppercase; color: var(--accent); margin-bottom: 8px; }
    .ph-title { margin: 0; font-size: 30px; font-weight: 500; letter-spacing: -0.015em; color: var(--fg); }
    .ph-sub { margin-top: 6px; font-size: 13.5px; color: var(--fg-muted); max-width: 620px; line-height: 1.5; }
    .ph-preview-badge {
      display: inline-flex; align-items: center; gap: 6px; flex-shrink: 0;
      font-size: 11px; font-weight: 600; letter-spacing: 0.05em; text-transform: uppercase;
      padding: 5px 12px; border-radius: 999px;
      background: oklch(from var(--accent) l c h / 0.14); color: var(--accent);
      border: 1px solid oklch(from var(--accent) l calc(c*.5) h / .4);
    }

    /* ── Preview banner ─────────────────────────────────────── */
    .ph-banner {
      display: flex; align-items: flex-start; gap: 12px;
      padding: 13px 16px; margin-bottom: 24px;
      background: var(--info-bg); border: 1px solid oklch(from var(--info) l calc(c*.5) h / .35);
      border-radius: var(--r-lg); color: var(--fg-muted); font-size: 12.5px; line-height: 1.5;
    }
    .ph-banner svg { color: var(--info); flex-shrink: 0; margin-top: 1px; }
    .ph-banner strong { color: var(--fg); font-weight: 600; }

    /* ── Search ─────────────────────────────────────────────── */
    .ph-search-row { display: flex; align-items: center; gap: 12px; margin-bottom: 20px; flex-wrap: wrap; }
    .ph-search-wrap { position: relative; flex: 1; min-width: 240px; max-width: 460px; display: flex; align-items: center; }
    .ph-search-icon { position: absolute; left: 12px; color: var(--fg-dim); pointer-events: none; }
    .ph-search-input {
      width: 100%; padding: 9px 32px 9px 36px;
      background: var(--surface); border: 1px solid var(--border);
      border-radius: var(--r); font: inherit; font-size: 13.5px; color: var(--fg);
      outline: none; transition: border-color .12s, box-shadow .12s;
    }
    .ph-search-input::placeholder { color: var(--fg-dim); }
    .ph-search-input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px oklch(from var(--accent) l c h / 0.15); }
    .ph-search-clear {
      position: absolute; right: 8px; appearance: none; border: 0; background: transparent;
      padding: 4px; border-radius: 4px; cursor: pointer; color: var(--fg-dim); display: grid; place-items: center;
    }
    .ph-search-clear:hover { color: var(--fg); background: var(--surface-3); }
    .ph-search-note { font-size: 12px; color: var(--fg-dim); white-space: nowrap; }

    /* ── Layout ─────────────────────────────────────────────── */
    .ph-grid { display: grid; grid-template-columns: 300px 1fr; gap: 18px; align-items: start; }

    /* ── Watchlist ──────────────────────────────────────────── */
    .ph-watchlist {
      background: var(--surface); border: 1px solid var(--border);
      border-radius: var(--r-lg); box-shadow: var(--shadow-1);
      padding: 8px; display: flex; flex-direction: column; gap: 2px;
    }
    .ph-wl-hd { font-size: 10.5px; font-weight: 600; letter-spacing: 0.07em; text-transform: uppercase; color: var(--fg-dim); padding: 8px 10px 6px; }
    .ph-wl-empty { padding: 14px 10px; font-size: 12.5px; color: var(--fg-dim); }
    .ph-wl-item {
      appearance: none; border: 0; background: transparent; text-align: left; cursor: pointer;
      border-radius: var(--r); padding: 10px 11px; font: inherit;
      display: flex; align-items: center; justify-content: space-between; gap: 10px;
      transition: background .1s;
    }
    .ph-wl-item:hover { background: var(--surface-2); }
    .ph-wl-item.is-on { background: oklch(from var(--accent) l c h / 0.12); box-shadow: inset 2px 0 0 var(--accent); }
    .ph-wl-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
    .ph-wl-desc { font-size: 13px; font-weight: 500; color: var(--fg); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .ph-wl-vendor { font-size: 11px; color: var(--fg-dim); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .ph-wl-right { display: flex; flex-direction: column; align-items: flex-end; gap: 2px; flex-shrink: 0; }
    .ph-wl-price { font-size: 13px; font-weight: 600; color: var(--fg); }
    .ph-wl-chg { font-size: 11px; font-weight: 600; }
    .ph-wl-chg.is-up { color: var(--bad); }
    .ph-wl-chg.is-down { color: var(--ok); }

    /* ── Tracking sheet ─────────────────────────────────────── */
    .ph-sheet { background: var(--surface); border: 1px solid var(--border); border-radius: var(--r-lg); box-shadow: var(--shadow-1); overflow: hidden; }
    .ph-sheet-hd { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 18px 20px; border-bottom: 1px solid var(--border); }
    .ph-sheet-desc { font-size: 17px; font-weight: 600; letter-spacing: -0.01em; color: var(--fg); }
    .ph-sheet-vendor { font-size: 12.5px; color: var(--fg-muted); margin-top: 2px; }
    .ph-spark { flex-shrink: 0; }

    .ph-kpis { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1px; background: var(--border); border-bottom: 1px solid var(--border); }
    .ph-kpi { background: var(--surface); padding: 14px 16px; }
    .ph-kpi-label { font-size: 10px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--fg-dim); margin-bottom: 5px; }
    .ph-kpi-val { font-size: 19px; font-weight: 700; letter-spacing: -0.02em; color: var(--fg); }
    .ph-kpi-val.is-bad { color: var(--bad); }
    .ph-kpi-val.is-ok { color: var(--ok); }
    .ph-kpi-sm { font-size: 14px; }

    .ph-table-wrap { overflow-x: auto; }
    .ph-table { width: 100%; min-width: 540px; border-collapse: collapse; font-size: 13px; }
    .ph-table thead th {
      padding: 10px 16px; font-size: 10.5px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em;
      color: var(--fg-dim); text-align: left; border-bottom: 1px solid var(--border); background: var(--surface-2);
    }
    .ph-table tbody td { padding: 11px 16px; border-bottom: 1px solid var(--border); color: var(--fg); white-space: nowrap; }
    .ph-table tbody tr:last-child td { border-bottom: 0; }
    .ph-table tbody tr:hover { background: var(--surface-2); }
    .ph-r { text-align: right; }
    .ph-inv { color: var(--fg-muted); font-size: 12px; }
    .ph-job { color: var(--accent); font-size: 12px; }
    .ph-unit { font-weight: 600; }
    .ph-up { color: var(--bad); font-weight: 600; }
    .ph-down { color: var(--ok); font-weight: 600; }
    .ph-base { color: var(--fg-dim); font-size: 11px; font-style: italic; }

    .ph-foot-note {
      display: flex; align-items: flex-start; gap: 9px;
      padding: 13px 20px; font-size: 12px; color: var(--fg-dim); line-height: 1.5;
      border-top: 1px solid var(--border); background: var(--surface-2);
    }
    .ph-foot-note svg { color: var(--fg-dim); flex-shrink: 0; margin-top: 1px; }

    @media (max-width: 820px) {
      .ph-grid { grid-template-columns: 1fr; }
      .ph-kpis { grid-template-columns: repeat(2, 1fr); }
    }
  `}</style>
);

Object.assign(window, { PriceHistoryView });
