/* AIWine CRM — Wine catalogue + Portal uploads */

function Wines({ country }) {
  const store = window.UI.useStore();
  const { Badge, Search, Ic, rel, money } = window.UI;
  const [q, setQ] = React.useState('');
  const [variety, setVariety] = React.useState('ALL');
  const [stock, setStock] = React.useState('ALL');
  const [open, setOpen] = React.useState(null);

  const all = store.t('wines').filter((v) => window.UI.inCountry(v, country));
  const varieties = ['ALL'].concat([...new Set(all.map((v) => v.variety))].sort());
  const rows = all.filter((v) => {
    const w = store.get('wineries', v.wineryId);
    return (q === '' || v.name.toLowerCase().includes(q.toLowerCase()) || (w && w.name.toLowerCase().includes(q.toLowerCase()))) &&
      (variety === 'ALL' || v.variety === variety) && (stock === 'ALL' || v.stock === stock);
  }).sort((a, b) => a.name.localeCompare(b.name));
  const sel = open ? store.get('wines', open) : null;
  const selWinery = sel ? store.get('wineries', sel.wineryId) : null;

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="label" style={{ marginBottom: 6 }}>{all.length} wines · {all.filter((v) => v.status === 'live').length} live · {all.filter((v) => v.enrichment !== 'complete').length} awaiting AI enrichment</div>
          <h1 className="page-title">Wine catalogue</h1>
        </div>
        <button className="btn btn-ghost" onClick={() => store.exportTableCSV('wines')}><Ic name="download" w={15} /> Export CSV</button>
      </div>
      <div className="filters">
        <Search value={q} onChange={setQ} placeholder="Search wine or winery…" />
        <select className="select" style={{ width: 180 }} value={variety} onChange={(e) => setVariety(e.target.value)}>
          {varieties.map((v) => <option key={v} value={v}>{v === 'ALL' ? 'All varieties' : v}</option>)}
        </select>
        <window.UI.Seg options={[{ value: 'ALL', label: 'All stock' }, { value: 'in', label: 'In' }, { value: 'low', label: 'Low' }, { value: 'out', label: 'Out' }]} value={stock} onChange={setStock} />
      </div>
      <div className="tbl-wrap">
        <table className="tbl">
          <thead><tr><th>Wine</th><th>Winery</th><th>Vintage</th><th>Price</th><th>Stock</th><th>Status</th><th>Enrichment</th></tr></thead>
          <tbody>
            {rows.slice(0, 120).map((v) => {
              const w = store.get('wineries', v.wineryId);
              return (
                <tr key={v.id} className="rowlink" onClick={() => setOpen(v.id)}>
                  <td className="main-cell"><window.VarietyDot variety={v.variety} /> {v.name}<div className="sub">{v.variety} · {v.vintage}</div></td>
                  <td style={{ fontSize: 12.5 }}>{w ? w.name : '—'}</td>
                  <td className="num">{v.vintage}</td>
                  <td className="num">{money(v.price, v.country)}</td>
                  <td><Badge v={v.stock}>{v.stock === 'in' ? 'In stock' : v.stock === 'low' ? 'Low' : 'Out'}</Badge></td>
                  <td><Badge v={v.status} /></td>
                  <td><Badge v={v.enrichment} /></td>
                </tr>
              );
            })}
            {rows.length === 0 && <tr><td colSpan="7"><window.UI.Empty msg="No wines match" /></td></tr>}
          </tbody>
        </table>
      </div>
      {rows.length > 120 && <div className="label" style={{ marginTop: 10 }}>Showing first 120 of {rows.length} — refine your search</div>}

      {sel && <WineEditor v={sel} w={selWinery} onClose={() => setOpen(null)} />}
    </div>
  );
}

function WineEditor({ v, w, onClose }) {
  const store = window.UI.useStore();
  const { Field, toast } = window.UI;
  const [f, setF] = React.useState({ ...v });
  const save = async () => {
    await store.update('wines', v.id, { name: f.name, vintage: Number(f.vintage), price: Number(f.price), stock: f.stock, status: f.status, enrichment: f.enrichment, updatedAt: new Date().toISOString() });
    store.audit('Edited wine ' + f.name, 'wine');
    toast('Wine updated'); onClose();
  };
  const del = async () => {
    if (!confirm('Delete “' + v.name + '”? This removes it from the catalogue for good.')) return;
    await store.remove('wines', v.id);
    store.audit('Deleted wine ' + v.name, 'wine');
    toast('Wine deleted'); onClose();
  };
  return (
    <window.UI.Drawer title={v.name} sub={w ? w.name + ' · ' + w.region : 'Wine'} onClose={onClose}
      foot={<React.Fragment><button className="btn btn-danger btn-sm" style={{ marginRight: 'auto' }} onClick={del}>Delete</button><button className="btn btn-ghost" onClick={onClose}>Cancel</button><button className="btn btn-primary" onClick={save}>Save changes</button></React.Fragment>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="Wine name"><input className="input" value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} /></Field>
        <div className="grid-2">
          <Field label="Vintage"><input className="input" type="number" value={f.vintage} onChange={(e) => setF({ ...f, vintage: e.target.value })} /></Field>
          <Field label={'Price (' + (v.country === 'AU' ? 'AUD' : 'NZD') + ')'}><input className="input" type="number" value={f.price} onChange={(e) => setF({ ...f, price: e.target.value })} /></Field>
        </div>
        <div className="grid-2">
          <Field label="Stock"><select className="select" value={f.stock} onChange={(e) => setF({ ...f, stock: e.target.value })}><option value="in">In stock</option><option value="low">Low</option><option value="out">Out of stock</option></select></Field>
          <Field label="Listing status"><select className="select" value={f.status} onChange={(e) => setF({ ...f, status: e.target.value })}><option value="live">Live</option><option value="draft">Draft</option><option value="archived">Archived</option></select></Field>
        </div>
        <Field label="AI enrichment"><select className="select" value={f.enrichment} onChange={(e) => setF({ ...f, enrichment: e.target.value })}><option value="pending">Pending</option><option value="partial">Partial</option><option value="complete">Complete</option></select></Field>
        <div className="card card-pad" style={{ fontSize: 12.5, color: 'var(--muted)', background: 'var(--card-2)' }}>
          Changes here ripple to {window.CRM_CONFIG.BRANDS[v.country || 'NZ'].domain} the next time the site syncs from the database.
        </div>
      </div>
    </window.UI.Drawer>
  );
}

function Uploads({ country }) {
  const store = window.UI.useStore();
  const { Badge, CTag, Ic, rel } = window.UI;
  const [flt, setFlt] = React.useState('ALL');
  const [imp, setImp] = React.useState(false);
  const rows = store.t('uploads').map((u) => ({ ...u, winery: store.get('wineries', u.wineryId) }))
    .filter((u) => u.winery && window.UI.inCountry(u.winery, country))
    .filter((u) => flt === 'ALL' || u.status === flt)
    .sort((a, b) => b.at.localeCompare(a.at));

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="label" style={{ marginBottom: 6 }}>{store.t('wines').length} wines in catalogue · {rows.filter((u) => u.status === 'needs review').length} upload{rows.filter((u) => u.status === 'needs review').length === 1 ? '' : 's'} need review</div>
          <h1 className="page-title">Portal uploads</h1>
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <window.UI.Seg options={[{ value: 'ALL', label: 'All' }, { value: 'processed', label: 'Processed' }, { value: 'needs review', label: 'Needs review' }]} value={flt} onChange={setFlt} />
          <button className="btn btn-primary" onClick={() => setImp(true)}><Ic name="upload" w={15} /> Import spreadsheet</button>
        </div>
      </div>
      <div className="tbl-wrap">
        <table className="tbl">
          <thead><tr><th>File</th><th>Winery</th><th></th><th>Rows</th><th>Status</th><th>When</th><th></th></tr></thead>
          <tbody>
            {rows.map((u) => (
              <tr key={u.id}>
                <td className="mono main-cell" style={{ fontSize: 12 }}>{u.filename}</td>
                <td><button className="btn-quiet" style={{ padding: 0, fontWeight: 600, color: 'var(--claret)' }} onClick={() => window.go('wineries', u.wineryId)}>{u.winery.name}</button></td>
                <td><CTag c={u.winery.country} /></td>
                <td className="num">{u.rows}</td>
                <td><Badge v={u.status} dot={u.status === 'needs review'} /></td>
                <td className="num">{rel(u.at)}</td>
                <td>{u.status === 'needs review' && <button className="btn btn-ghost btn-sm" onClick={() => { store.update('uploads', u.id, { status: 'processed' }); store.audit('Processed upload ' + u.filename, 'upload'); window.UI.toast('Marked processed'); }}>Mark processed</button>}</td>
              </tr>
            ))}
            {rows.length === 0 && <tr><td colSpan="7"><window.UI.Empty msg="No uploads yet" hint="Import a winery's stock list with the button above, or wait for portal uploads to land here." /></td></tr>}
          </tbody>
        </table>
      </div>
      {imp && <window.ImportFlow country={country} onClose={() => setImp(false)} onDone={() => window.UI.toast('Catalogue updated')} />}
    </div>
  );
}

Object.assign(window, { Wines, Uploads });
