/* AIWine CRM — Support tickets + Tasks */

function Support({ country, focusId }) {
  const store = window.UI.useStore();
  const { Badge, CTag, Search, Ic, rel } = window.UI;
  const [tab, setTab] = React.useState('open');
  const [open, setOpen] = React.useState(focusId || null);
  const [reply, setReply] = React.useState('');
  React.useEffect(() => { if (focusId) setOpen(focusId); }, [focusId]);

  const all = store.t('tickets').filter((t) => window.UI.inCountry(t, country));
  const rows = all.filter((t) => (tab === 'open' ? t.status !== 'closed' : t.status === 'closed'))
    .sort((a, b) => ({ high: 0, normal: 1, low: 2 }[a.priority] - { high: 0, normal: 1, low: 2 }[b.priority]) || b.createdAt.localeCompare(a.createdAt));
  const sel = open ? store.get('tickets', open) : null;

  const sendReply = async () => {
    if (!reply.trim() || !sel) return;
    await store.update('tickets', sel.id, { status: 'waiting', messages: sel.messages.concat([{ from: store.user.name, at: new Date().toISOString(), body: reply.trim() }]) });
    store.audit('Replied to ticket: ' + sel.subject, 'ticket');
    setReply(''); window.UI.toast('Reply sent' + (store.mode === 'demo' ? ' (demo)' : ' via Resend'));
  };

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="label" style={{ marginBottom: 6 }}>{all.filter((t) => t.status !== 'closed').length} open · {all.filter((t) => t.priority === 'high' && t.status !== 'closed').length} high priority</div>
          <h1 className="page-title">Support</h1>
        </div>
      </div>
      <window.UI.Tabs value={tab} onChange={setTab} items={[
        { id: 'open', label: 'Open', count: all.filter((t) => t.status !== 'closed').length },
        { id: 'closed', label: 'Closed' },
      ]} />
      <div className="tbl-wrap">
        <table className="tbl">
          <thead><tr><th>Ticket</th><th>From</th><th></th><th>Priority</th><th>Status</th><th>Assignee</th><th>Age</th></tr></thead>
          <tbody>
            {rows.map((t) => (
              <tr key={t.id} className="rowlink" onClick={() => setOpen(t.id)}>
                <td className="main-cell">{t.subject}<div className="sub">{t.kind === 'winery' ? 'Winery' : 'Consumer'}</div></td>
                <td style={{ fontSize: 12.5 }}>{t.from}</td>
                <td><CTag c={t.country} /></td>
                <td><Badge v={t.priority === 'high' ? 'open' : t.priority === 'normal' ? 'scheduled' : 'draft'}>{t.priority}</Badge></td>
                <td><Badge v={t.status} dot={t.status === 'open'} /></td>
                <td style={{ fontSize: 12.5 }}>{t.assignee}</td>
                <td className="num">{rel(t.createdAt)}</td>
              </tr>
            ))}
            {rows.length === 0 && <tr><td colSpan="7"><window.UI.Empty msg={tab === 'open' ? 'Inbox zero — no open tickets' : 'No closed tickets'} /></td></tr>}
          </tbody>
        </table>
      </div>

      {sel && (
        <window.UI.Drawer title={sel.subject} sub={(sel.kind === 'winery' ? 'Winery ticket' : 'Consumer ticket') + ' · ' + sel.from} onClose={() => { setOpen(null); if (focusId) window.go('support'); }}
          foot={<React.Fragment>
            {sel.status !== 'closed'
              ? <button className="btn btn-ghost" onClick={() => { store.update('tickets', sel.id, { status: 'closed' }); store.audit('Closed ticket: ' + sel.subject, 'ticket'); window.UI.toast('Ticket closed'); }}>Close ticket</button>
              : <button className="btn btn-ghost" onClick={() => { store.update('tickets', sel.id, { status: 'open' }); window.UI.toast('Ticket reopened'); }}>Reopen</button>}
            <button className="btn btn-primary" onClick={sendReply} disabled={!reply.trim()}><Ic name="send" w={14} /> Reply</button>
          </React.Fragment>}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <Badge v={sel.status} dot={sel.status === 'open'} />
              <Badge v={sel.priority === 'high' ? 'open' : 'draft'}>{sel.priority} priority</Badge>
              {sel.wineryId && <button className="btn-quiet" style={{ fontSize: 12, color: 'var(--claret)', fontWeight: 600 }} onClick={() => window.go('wineries', sel.wineryId)}>View winery →</button>}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {sel.messages.map((m, i) => {
                const mine = m.from !== sel.from;
                return (
                  <div key={i} className="card card-pad" style={{ background: mine ? 'var(--bone-alt)' : 'var(--card-2)', marginLeft: mine ? 28 : 0, marginRight: mine ? 0 : 28 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
                      <span style={{ fontSize: 12, fontWeight: 700 }}>{m.from}</span>
                      <span className="mono" style={{ fontSize: 10, color: 'var(--faint)' }}>{rel(m.at)}</span>
                    </div>
                    <div style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{m.body}</div>
                  </div>
                );
              })}
            </div>
            <textarea className="input" rows="3" placeholder={'Reply to ' + sel.from + '…'} value={reply} onChange={(e) => setReply(e.target.value)} />
          </div>
        </window.UI.Drawer>
      )}
    </div>
  );
}

function Tasks() {
  const store = window.UI.useStore();
  const { Badge, Ic, rel, fmtShort } = window.UI;
  const [adding, setAdding] = React.useState(false);
  const [showDone, setShowDone] = React.useState(false);

  const open = store.t('tasks').filter((t) => !t.done).sort((a, b) => a.due.localeCompare(b.due));
  const done = store.t('tasks').filter((t) => t.done);
  const now = new Date();
  const groups = [
    { label: 'Overdue', rows: open.filter((t) => new Date(t.due) < now && new Date(t.due).toDateString() !== now.toDateString()), tone: 'var(--claret)' },
    { label: 'Today & tomorrow', rows: open.filter((t) => { const d = new Date(t.due); return d >= now && d < new Date(Date.now() + 2 * 86400000) || d.toDateString() === now.toDateString(); }), tone: 'var(--brass)' },
    { label: 'Upcoming', rows: open.filter((t) => new Date(t.due) >= new Date(Date.now() + 2 * 86400000)), tone: 'var(--green)' },
  ];

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="label" style={{ marginBottom: 6 }}>{open.length} open · {done.length} done</div>
          <h1 className="page-title">Tasks</h1>
        </div>
        <button className="btn btn-primary" onClick={() => setAdding(true)}><Ic name="plus" w={15} /> Add task</button>
      </div>

      {groups.map((g) => g.rows.length > 0 && (
        <div key={g.label} style={{ marginBottom: 22 }}>
          <div className="label" style={{ marginBottom: 8, color: g.tone }}>{g.label} · {g.rows.length}</div>
          <div className="card">
            {g.rows.map((t) => <TaskRow key={t.id} t={t} />)}
          </div>
        </div>
      ))}
      {open.length === 0 && <window.UI.Empty msg="All clear — no open tasks" hint="Add one with the button above." />}

      {done.length > 0 && (
        <div style={{ marginTop: 8 }}>
          <button className="btn-quiet" style={{ fontSize: 12.5 }} onClick={() => setShowDone(!showDone)}>{showDone ? 'Hide' : 'Show'} {done.length} completed</button>
          {showDone && <div className="card" style={{ marginTop: 8, opacity: 0.65 }}>{done.map((t) => <TaskRow key={t.id} t={t} />)}</div>}
        </div>
      )}

      {adding && <window.AddTask wineryId={null} onClose={() => setAdding(false)} />}
    </div>
  );
}

function TaskRow({ t }) {
  const store = window.UI.useStore();
  const { rel } = window.UI;
  const w = t.wineryId ? store.get('wineries', t.wineryId) : null;
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'center', padding: '10px 16px', borderBottom: '1px solid var(--line-soft)' }}>
      <button className="btn-quiet" style={{ padding: 2 }} title={t.done ? 'Reopen' : 'Mark done'}
        onClick={() => { store.update('tasks', t.id, { done: !t.done }); if (!t.done) window.UI.toast('Task done'); }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 17, height: 17, border: '1.5px solid ' + (t.done ? 'var(--green)' : 'var(--line)'), borderRadius: 3, background: t.done ? 'var(--green)' : 'transparent', color: 'var(--bone)' }}>
          {t.done && <window.UI.Ic name="check" w={11} />}
        </span>
      </button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <span style={{ fontSize: 13.5, fontWeight: 600, textDecoration: t.done ? 'line-through' : 'none' }}>{t.title}</span>
        {w && <button className="btn-quiet" style={{ padding: '0 0 0 8px', fontSize: 12, color: 'var(--claret)', fontWeight: 600 }} onClick={() => window.go('wineries', w.id)}>{w.name}</button>}
      </div>
      <span className="badge">{t.type}</span>
      <span style={{ fontSize: 12, color: 'var(--muted)' }}>{t.assignee}</span>
      <span className="mono" style={{ fontSize: 10.5, color: !t.done && new Date(t.due) < new Date() ? 'var(--claret)' : 'var(--muted)', width: 64, textAlign: 'right' }}>{rel(t.due)}</span>
    </div>
  );
}

Object.assign(window, { Support, Tasks });
