/* AIWine CRM — Winery profile */
function WineryProfile({ id }) {
  const store = window.UI.useStore();
  const { Badge, CTag, Score, Ic, rel, fmtDate, KV, Field, toast, money } = window.UI;
  const w = store.get('wineries', id);
  const [tab, setTab] = React.useState('overview');
  const [editing, setEditing] = React.useState(false);
  const [noteText, setNoteText] = React.useState('');
  const [taskAdd, setTaskAdd] = React.useState(false);
  const [contactAdd, setContactAdd] = React.useState(false);
  const [contactEdit, setContactEdit] = React.useState(null);

  if (!w) return <window.UI.Empty msg="Winery not found" hint="It may have been removed." />;

  const contacts = store.t('contacts').filter((c) => c.wineryId === id);
  const wines = store.t('wines').filter((v) => v.wineryId === id);
  const uploads = store.t('uploads').filter((u) => u.wineryId === id).sort((a, b) => b.at.localeCompare(a.at));
  const notes = store.t('notes').filter((n) => n.wineryId === id).sort((a, b) => b.at.localeCompare(a.at));
  const tasks = store.t('tasks').filter((t) => t.wineryId === id && !t.done);

  const addNote = async () => {
    if (!noteText.trim()) return;
    await store.insert('notes', { wineryId: id, author: store.user.name, at: new Date().toISOString(), body: noteText.trim() });
    store.audit('Added note on ' + w.name, 'note');
    setNoteText(''); toast('Note saved');
  };

  return (
    <div>
      <button className="btn-quiet" style={{ marginBottom: 14, marginLeft: -10 }} onClick={() => window.go('wineries')}><Ic name="back" w={15} /> All wineries</button>

      <div className="page-head" style={{ alignItems: 'flex-start' }}>
        <div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 8 }}>
            <CTag c={w.country} />
            <Badge v={w.tier}>{window.UI.TIER_LABEL[w.tier]}</Badge>
            <Badge v={w.status} dot />
          </div>
          <h1 className="page-title" style={{ fontSize: 40 }}>{w.name}</h1>
          <p className="page-sub"><em className="serif" style={{ fontSize: 15 }}>{w.region}</em> · {w.website} · managed by {w.owner || '—'}</p>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn-ghost" onClick={() => setTaskAdd(true)}><Ic name="task" w={15} /> Add task</button>
          <button className="btn btn-primary" onClick={() => setEditing(true)}><Ic name="edit" w={15} /> Edit</button>
        </div>
      </div>

      <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', marginBottom: 20 }}>
        <ScoreTile label="Completeness" v={w.completeness} hint="listing data filled" />
        <ScoreTile label="Engagement" v={w.engagement} hint="portal + email activity" />
        <div className="stat-tile"><div className="label">AI enrichment</div><div style={{ marginTop: 10 }}><Badge v={w.enrichment} /></div><div className="delta" style={{ color: 'var(--muted)', marginTop: 8 }}>{wines.filter((x) => x.enrichment === 'complete').length}/{wines.length} wines enriched</div></div>
        <div className="stat-tile"><div className="label">Catalogue</div><div className="num" style={{ fontSize: 28 }}>{wines.length}</div><div className="delta" style={{ color: 'var(--muted)' }}>{wines.filter((x) => x.status === 'live').length} live · {wines.filter((x) => x.stock === 'out').length} out of stock</div></div>
        <div className="stat-tile"><div className="label">Last upload</div><div className="num" style={{ fontSize: 28 }}>{w.lastUpload ? rel(w.lastUpload).replace(' ago', '') : '—'}</div><div className="delta" style={{ color: w.status === 'stale' ? 'var(--claret)' : 'var(--muted)' }}>{w.status === 'stale' ? 'catalogue going stale' : (w.uploadCount + ' uploads total')}</div></div>
      </div>

      <window.UI.Tabs value={tab} onChange={setTab} items={[
        { id: 'overview', label: 'Overview' },
        { id: 'contacts', label: 'Contacts', count: contacts.length },
        { id: 'wines', label: 'Wines', count: wines.length },
        { id: 'uploads', label: 'Uploads', count: uploads.length },
      ]} />

      {tab === 'overview' && (
        <div className="split">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div className="card">
              <div className="card-head"><h3 className="card-title">Notes & interactions</h3></div>
              <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                <div style={{ display: 'flex', gap: 10 }}>
                  <textarea className="input" rows="2" placeholder={'Log a call, email or visit with ' + w.name + '…'} value={noteText} onChange={(e) => setNoteText(e.target.value)} />
                  <button className="btn btn-primary btn-sm" style={{ alignSelf: 'flex-end' }} onClick={addNote}>Save</button>
                </div>
                {notes.map((n) => (
                  <div key={n.id} style={{ borderTop: '1px solid var(--line-soft)', paddingTop: 10 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 3 }}>
                      <span style={{ fontSize: 12, fontWeight: 700 }}>{n.author}</span>
                      <span className="mono" style={{ fontSize: 10, color: 'var(--faint)' }}>{rel(n.at)}</span>
                    </div>
                    <div style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{n.body}</div>
                  </div>
                ))}
                {notes.length === 0 && <div style={{ fontSize: 12.5, color: 'var(--muted)' }}>No notes yet — log the first interaction above.</div>}
              </div>
            </div>
            {tasks.length > 0 && (
              <div className="card">
                <div className="card-head"><h3 className="card-title">Open tasks</h3></div>
                <div className="card-pad" style={{ paddingTop: 8 }}>
                  {tasks.map((t) => (
                    <div key={t.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 0', borderBottom: '1px solid var(--line-soft)' }}>
                      <span style={{ fontSize: 13, fontWeight: 600 }}>{t.title}</span>
                      <span style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                        <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>{rel(t.due)}</span>
                        <button className="btn btn-ghost btn-sm" onClick={() => { store.update('tasks', t.id, { done: true }); toast('Task done'); }}>Done</button>
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
          <div className="card card-pad">
            <h3 className="card-title" style={{ marginBottom: 14 }}>Details</h3>
            <KV rows={[
              ['Email', w.email], ['Phone', w.phone], ['Website', w.website],
              ['Address', w.address],
              ['Region', w.region], ['Market', window.CRM_CONFIG.BRANDS[w.country].domain],
              ['Tier', window.UI.TIER_LABEL[w.tier]], ['Owner', w.owner],
              ['Added', fmtDate(w.createdAt)],
            ]} />
          </div>
        </div>
      )}

      {tab === 'contacts' && (
        <div>
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 12 }}>
            <button className="btn btn-ghost btn-sm" onClick={() => setContactAdd(true)}><Ic name="plus" w={14} /> Add contact</button>
          </div>
          <div className="tbl-wrap">
            <table className="tbl">
              <thead><tr><th>Name</th><th>Role</th><th>Email</th><th>Phone</th><th>Email opt-in</th><th></th></tr></thead>
              <tbody>
                {contacts.map((c) => (
                  <tr key={c.id} className="rowlink" onClick={() => setContactEdit(c.id)}>
                    <td className="main-cell" style={{ display: 'flex', alignItems: 'center', gap: 10 }}><window.UI.Avatar name={c.name} brass={!c.primary} />{c.name}{c.primary && <span className="badge badge-brass">Primary</span>}</td>
                    <td>{c.role}</td>
                    <td className="mono" style={{ fontSize: 11.5 }}>{c.email}</td>
                    <td className="mono" style={{ fontSize: 11.5 }}>{c.phone}</td>
                    <td>{c.subscribed ? <Badge v="complete">Subscribed</Badge> : <Badge v="pending">Unsubscribed</Badge>}</td>
                    <td onClick={(e) => e.stopPropagation()} style={{ whiteSpace: 'nowrap' }}>
                      <button className="btn-quiet" title="Edit" onClick={() => setContactEdit(c.id)}><Ic name="edit" w={14} c="var(--muted)" /></button>
                      <button className="btn-quiet" title="Remove" onClick={() => { if (confirm('Remove ' + c.name + '?')) { store.remove('contacts', c.id); store.audit('Removed contact ' + c.name, 'contact'); } }}><Ic name="trash" w={14} c="var(--muted)" /></button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'wines' && (
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>Wine</th><th>Vintage</th><th>Price</th><th>Stock</th><th>Status</th><th>Enrichment</th><th>Updated</th></tr></thead>
            <tbody>
              {wines.map((v) => (
                <tr key={v.id}>
                  <td className="main-cell"><VarietyDot variety={v.variety} /> {v.name}<div className="sub">{v.variety}</div></td>
                  <td className="num">{v.vintage}</td>
                  <td className="num">{money(v.price, w.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>
                  <td className="num">{rel(v.updatedAt)}</td>
                </tr>
              ))}
              {wines.length === 0 && <tr><td colSpan="7"><window.UI.Empty msg="No wines yet" hint="Wines appear when the winery uploads through the portal." /></td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'uploads' && (
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>File</th><th>Rows</th><th>Status</th><th>When</th></tr></thead>
            <tbody>
              {uploads.map((u) => (
                <tr key={u.id}>
                  <td className="mono main-cell" style={{ fontSize: 12 }}>{u.filename}</td>
                  <td className="num">{u.rows}</td>
                  <td><Badge v={u.status} /></td>
                  <td className="num">{rel(u.at)}</td>
                </tr>
              ))}
              {uploads.length === 0 && <tr><td colSpan="4"><window.UI.Empty msg="No portal uploads yet" hint="Send them their portal invite to get the catalogue flowing." /></td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {editing && <EditWinery w={w} onClose={() => setEditing(false)} />}
      {taskAdd && <AddTask wineryId={id} onClose={() => setTaskAdd(false)} />}
      {contactAdd && <AddContact wineryId={id} onClose={() => setContactAdd(false)} />}
      {contactEdit && <EditContact id={contactEdit} onClose={() => setContactEdit(null)} />}
    </div>
  );
}

function ScoreTile({ label, v, hint }) {
  return (
    <div className="stat-tile">
      <div className="label">{label}</div>
      <div className="num" style={{ fontSize: 28 }}>{v}<span style={{ fontSize: 16, color: 'var(--faint)' }}>/100</span></div>
      <window.UI.Score v={v} />
      <div className="delta" style={{ color: 'var(--muted)', marginTop: 6 }}>{hint}</div>
    </div>
  );
}

const VARIETY_TINT = { 'Pinot Noir': 'var(--t-pinot)', 'Syrah': 'var(--t-syrah)', 'Shiraz': 'var(--t-shiraz)', 'Chardonnay': 'var(--t-chard)', 'Sauvignon Blanc': 'var(--t-sauv)', 'Pinot Gris': 'var(--t-pinotg)', 'Riesling': 'var(--t-ries)', 'Rosé': 'var(--t-rose)', 'Merlot': 'var(--t-merlot)', 'Cabernet Sauvignon': 'var(--t-cab)', 'Sparkling': 'var(--t-sparkling)', 'Gewürztraminer': 'var(--t-gewurz)', 'Grenache': 'var(--t-grenache)', 'Semillon': 'var(--t-semillon)' };
function VarietyDot({ variety }) {
  return <span style={{ display: 'inline-block', width: 9, height: 9, borderRadius: '50%', background: VARIETY_TINT[variety] || 'var(--claret)', marginRight: 4, verticalAlign: 'baseline' }}></span>;
}

function EditWinery({ w, onClose }) {
  const store = window.UI.useStore();
  const { Field, toast } = window.UI;
  const [f, setF] = React.useState({ ...w });
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const save = async () => {
    const patch = { name: f.name, region: f.region, email: f.email, phone: f.phone, website: f.website, tier: f.tier, status: f.status, owner: f.owner, country: f.country };
    await store.update('wineries', w.id, patch);
    store.audit('Updated winery ' + f.name, 'winery');
    toast('Winery updated'); onClose();
  };
  return (
    <window.UI.Drawer title={'Edit ' + w.name} sub="Winery record" onClose={onClose}
      foot={<React.Fragment>
        <button className="btn btn-danger btn-sm" style={{ marginRight: 'auto' }} onClick={() => { if (confirm('Archive ' + w.name + '? It moves to Churned status — contacts, wines and history are all kept, and you can restore it anytime by changing the status back.')) { store.update('wineries', w.id, { status: 'churned' }); store.audit('Archived winery ' + w.name, 'winery'); window.UI.toast('Archived — find it under status: Churned'); onClose(); } }}>Archive</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="Name"><input className="input" value={f.name} onChange={set('name')} /></Field>
        <div className="grid-2">
          <Field label="Market"><select className="select" value={f.country} onChange={set('country')}><option value="NZ">New Zealand</option><option value="AU">Australia</option></select></Field>
          <Field label="Region"><input className="input" value={f.region} onChange={set('region')} /></Field>
        </div>
        <div className="grid-2">
          <Field label="Tier"><select className="select" value={f.tier} onChange={set('tier')}><option value="prospect">Prospect</option><option value="listed">Listed</option><option value="partner">Partner</option><option value="founding">Founding</option></select></Field>
          <Field label="Status"><select className="select" value={f.status} onChange={set('status')}><option value="prospect">Prospect</option><option value="onboarding">Onboarding</option><option value="active">Active</option><option value="stale">Stale</option><option value="churned">Churned</option></select></Field>
        </div>
        <div className="grid-2">
          <Field label="Email"><input className="input" value={f.email} onChange={set('email')} /></Field>
          <Field label="Phone"><input className="input" value={f.phone} onChange={set('phone')} /></Field>
        </div>
        <div className="grid-2">
          <Field label="Website"><input className="input" value={f.website} onChange={set('website')} /></Field>
          <Field label="Account owner"><input className="input" value={f.owner || ''} onChange={set('owner')} /></Field>
        </div>
      </div>
    </window.UI.Drawer>
  );
}

function AddTask({ wineryId, onClose }) {
  const store = window.UI.useStore();
  const { Field, toast } = window.UI;
  const [f, setF] = React.useState({ title: '', type: 'call', due: new Date(Date.now() + 86400000).toISOString().slice(0, 10) });
  const save = async () => {
    if (!f.title.trim()) { toast('Give the task a title'); return; }
    await store.insert('tasks', { title: f.title.trim(), type: f.type, due: new Date(f.due + 'T09:00:00').toISOString(), wineryId: wineryId || null, assignee: store.user.name, done: false });
    store.audit('Added task: ' + f.title, 'task');
    toast('Task added'); onClose();
  };
  return (
    <window.UI.Modal title="Add task" sub="Reminder" onClose={onClose}
      foot={<React.Fragment><button className="btn btn-ghost" onClick={onClose}>Cancel</button><button className="btn btn-primary" onClick={save}>Add task</button></React.Fragment>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="What needs doing?"><input className="input" value={f.title} onChange={(e) => setF({ ...f, title: e.target.value })} autoFocus /></Field>
        <div className="grid-2">
          <Field label="Type"><select className="select" value={f.type} onChange={(e) => setF({ ...f, type: e.target.value })}><option value="call">Call</option><option value="email">Email</option><option value="follow-up">Follow-up</option><option value="review">Review</option></select></Field>
          <Field label="Due"><input className="input" type="date" value={f.due} onChange={(e) => setF({ ...f, due: e.target.value })} /></Field>
        </div>
      </div>
    </window.UI.Modal>
  );
}

function AddContact({ wineryId, onClose }) {
  const store = window.UI.useStore();
  const { Field, toast } = window.UI;
  const [f, setF] = React.useState({ name: '', role: '', email: '', phone: '' });
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const save = async () => {
    if (!f.name.trim()) { toast('Name is required'); return; }
    try { await store.insert('contacts', { ...f, wineryId, primary: false, subscribed: true }); }
    catch (err) { toast(err.message); return; }
    store.audit('Added contact ' + f.name, 'contact');
    toast('Contact added'); onClose();
  };
  return (
    <window.UI.Modal title="Add contact" sub="Winery contact" onClose={onClose}
      foot={<React.Fragment><button className="btn btn-ghost" onClick={onClose}>Cancel</button><button className="btn btn-primary" onClick={save}>Add contact</button></React.Fragment>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div className="grid-2">
          <Field label="Name"><input className="input" value={f.name} onChange={set('name')} autoFocus /></Field>
          <Field label="Role"><input className="input" value={f.role} onChange={set('role')} placeholder="e.g. Winemaker" /></Field>
        </div>
        <div className="grid-2">
          <Field label="Email"><input className="input" value={f.email} onChange={set('email')} /></Field>
          <Field label="Phone"><input className="input" value={f.phone} onChange={set('phone')} /></Field>
        </div>
      </div>
    </window.UI.Modal>
  );
}

function EditContact({ id, onClose }) {
  const store = window.UI.useStore();
  const { Field, toast } = window.UI;
  const c = store.get('contacts', id);
  const [f, setF] = React.useState(c ? { ...c } : {});
  if (!c) return null;
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const save = async () => {
    if (!f.name.trim()) { toast('Name is required'); return; }
    await store.update('contacts', id, { name: f.name.trim(), role: f.role, email: (f.email || '').trim().toLowerCase(), phone: f.phone, primary: !!f.primary, subscribed: !!f.subscribed });
    if (f.primary && !c.primary) {
      // only one primary per winery
      for (const other of store.t('contacts').filter((x) => x.wineryId === c.wineryId && x.id !== id && x.primary)) {
        await store.update('contacts', other.id, { primary: false });
      }
    }
    store.audit('Edited contact ' + f.name, 'contact');
    toast('Contact updated'); onClose();
  };
  return (
    <window.UI.Drawer title={'Edit ' + c.name} sub="Contact record" onClose={onClose}
      foot={<React.Fragment>
        <button className="btn btn-danger btn-sm" style={{ marginRight: 'auto' }} onClick={() => { if (confirm('Remove ' + c.name + '?')) { store.remove('contacts', id); store.audit('Removed contact ' + c.name, 'contact'); onClose(); } }}>Remove</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 }}>
        <div className="grid-2">
          <Field label="Name"><input className="input" value={f.name} onChange={set('name')} autoFocus /></Field>
          <Field label="Role"><input className="input" value={f.role || ''} onChange={set('role')} placeholder="e.g. Winemaker" /></Field>
        </div>
        <div className="grid-2">
          <Field label="Email"><input className="input" value={f.email || ''} onChange={set('email')} /></Field>
          <Field label="Phone"><input className="input" value={f.phone || ''} onChange={set('phone')} /></Field>
        </div>
        <label style={{ display: 'flex', gap: 9, alignItems: 'center', fontSize: 13 }}>
          <input type="checkbox" checked={!!f.primary} onChange={(e) => setF({ ...f, primary: e.target.checked })} /> Primary contact for this winery
        </label>
        <label style={{ display: 'flex', gap: 9, alignItems: 'center', fontSize: 13 }}>
          <input type="checkbox" checked={!!f.subscribed} onChange={(e) => setF({ ...f, subscribed: e.target.checked })} /> Subscribed to marketing email
        </label>
        {!f.subscribed && <div style={{ fontSize: 12, color: 'var(--brass)' }}>Unsubscribed contacts are excluded from every campaign automatically.</div>}
      </div>
    </window.UI.Drawer>
  );
}

Object.assign(window, { WineryProfile, AddTask, EditContact, VarietyDot, VARIETY_TINT });
