/* AIWine CRM — Dashboard */
function Dashboard({ country }) {
  const store = window.UI.useStore();
  const { StatTile, Badge, Ic, rel, inCountry } = window.UI;
  const F = (rows) => rows.filter((r) => inCountry(r, country));

  const wineries = F(store.t('wineries'));
  const consumers = F(store.t('consumers'));
  const contacts = store.t('contacts').filter((c) => { const w = store.get('wineries', c.wineryId); return w && inCountry(w, country); });
  const premium = consumers.filter((c) => c.plan === 'premium');
  const renewalsDue = premium.filter((c) => c.renewsAt && new Date(c.renewsAt) < new Date(Date.now() + 30 * 86400000));
  const openTickets = F(store.t('tickets')).filter((t) => t.status !== 'closed');
  const stale = wineries.filter((w) => w.status === 'stale');
  const activities = store.t('activities');
  const tasksDue = store.t('tasks').filter((t) => !t.done).sort((a, b) => a.due.localeCompare(b.due)).slice(0, 6);
  const flaggedUploads = store.t('uploads').filter((u) => u.status === 'needs review');

  const FEED_ICON = { upload: 'upload', signup: 'consumer', ticket: 'ticket', campaign: 'mail', renewal: 'member' };
  const hour = new Date().getHours();
  const part = hour < 12 ? 'morning' : hour < 17 ? 'afternoon' : 'evening';

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="label" style={{ marginBottom: 6 }}>{country === 'ALL' ? 'aiwine.co.nz + aiwine.com.au' : window.CRM_CONFIG.BRANDS[country].domain} · {new Date().toLocaleDateString('en-NZ', { weekday: 'long', day: 'numeric', month: 'long' })}</div>
          <h1 className="page-title">Good {part},<br /><em>{store.user ? store.user.name.split(' ')[0] : ''}.</em></h1>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn-ghost" onClick={() => window.go('campaigns')}><Ic name="mail" w={15} /> New campaign</button>
          <button className="btn btn-primary" onClick={() => window.go('wineries')}><Ic name="plus" w={15} /> Add winery</button>
        </div>
      </div>

      <div className="stat-grid" style={{ marginBottom: 18 }}>
        <StatTile label="Wineries" num={wineries.length} delta={wineries.filter((w) => w.status === 'active').length + ' active'} onClick={() => window.go('wineries')} />
        <StatTile label="Contacts" num={contacts.length} delta={contacts.filter((c) => c.subscribed).length + ' subscribed'} onClick={() => window.go('contacts')} />
        <StatTile label="Consumers" num={consumers.length} delta={'+' + consumers.filter((c) => (Date.now() - new Date(c.joined)) / 86400000 < 30).length + ' this month'} onClick={() => window.go('consumers')} />
        <StatTile label="Premium subs" num={premium.length} delta={Math.round((premium.length / Math.max(consumers.length, 1)) * 100) + '% of base'} onClick={() => window.go('memberships')} />
        <StatTile label="Renewals due" num={renewalsDue.length} delta="next 30 days" deltaClass={renewalsDue.length ? 'warn' : 'up'} onClick={() => window.go('memberships')} />
        <StatTile label="Open tickets" num={openTickets.length} delta={openTickets.filter((t) => t.priority === 'high').length + ' high priority'} deltaClass={openTickets.some((t) => t.priority === 'high') ? 'bad' : 'up'} onClick={() => window.go('support')} />
      </div>

      <div className="split">
        <div className="card">
          <div className="card-head">
            <h3 className="card-title">Recent activity</h3>
            <span className="label" style={{ fontSize: 9 }}>Portal · app · billing</span>
          </div>
          <div className="card-pad feed" style={{ paddingTop: 8, paddingBottom: 8 }}>
            {activities.slice(0, 12).map((a, i) => (
              <div key={i} className="feed-item" style={{ cursor: a.ref ? 'pointer' : 'default' }} onClick={() => a.ref && window.go(a.ref.page, a.ref.id)}>
                <span className="feed-ic"><Ic name={FEED_ICON[a.type] || 'sparkle'} w={14} /></span>
                <span className="feed-body">{a.text}</span>
                <span className="feed-when">{rel(a.at)}</span>
              </div>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="card">
            <div className="card-head">
              <h3 className="card-title">Tasks due</h3>
              <button className="btn-quiet" style={{ fontSize: 12 }} onClick={() => window.go('tasks')}>All tasks</button>
            </div>
            <div className="card-pad" style={{ paddingTop: 6, paddingBottom: 10, display: 'flex', flexDirection: 'column' }}>
              {tasksDue.length === 0 && <window.UI.Empty msg="No open tasks" />}
              {tasksDue.map((t) => {
                const w = t.wineryId ? store.get('wineries', t.wineryId) : null;
                const overdue = new Date(t.due) < new Date();
                return (
                  <div key={t.id} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '8px 0', borderBottom: '1px solid var(--line-soft)' }}>
                    <button className="btn-quiet" style={{ padding: 2, marginTop: 1, color: 'var(--muted)' }} title="Mark done"
                      onClick={() => { store.update('tasks', t.id, { done: true }); window.UI.toast('Task done'); }}>
                      <span style={{ display: 'inline-block', width: 15, height: 15, border: '1.5px solid var(--line)', borderRadius: 3 }}></span>
                    </button>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600 }}>{t.title}</div>
                      {w && <button className="btn-quiet" style={{ padding: 0, fontSize: 11.5, color: 'var(--claret)', fontWeight: 600 }} onClick={() => window.go('wineries', w.id)}>{w.name}</button>}
                    </div>
                    <span className="mono" style={{ fontSize: 10, color: overdue ? 'var(--claret)' : 'var(--muted)', whiteSpace: 'nowrap', paddingTop: 3 }}>{rel(t.due)}</span>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h3 className="card-title">Needs attention</h3></div>
            <div className="card-pad" style={{ paddingTop: 10, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <AttentionRow icon="alert" tone="var(--claret)" label={stale.length + ' winer' + (stale.length === 1 ? 'y' : 'ies') + ' with stale catalogues'} hint="No upload in 60+ days" onClick={() => window.go('wineries')} />
              <AttentionRow icon="upload" tone="var(--brass)" label={flaggedUploads.length + ' upload' + (flaggedUploads.length === 1 ? '' : 's') + ' need review'} hint="Flagged by the portal" onClick={() => window.go('uploads')} />
              <AttentionRow icon="member" tone="var(--green)" label={renewalsDue.length + ' renewals in the next 30 days'} hint="Send the reminder campaign" onClick={() => window.go('memberships')} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function AttentionRow({ icon, tone, label, hint, onClick }) {
  const { Ic } = window.UI;
  return (
    <button className="btn-quiet" style={{ display: 'flex', gap: 12, alignItems: 'center', textAlign: 'left', padding: '8px 10px', width: '100%' }} onClick={onClick}>
      <span className="feed-ic" style={{ color: tone }}><Ic name={icon} w={14} /></span>
      <span style={{ flex: 1 }}>
        <span style={{ display: 'block', fontSize: 13, fontWeight: 600 }}>{label}</span>
        <span style={{ display: 'block', fontSize: 11.5, color: 'var(--muted)' }}>{hint}</span>
      </span>
      <Ic name="chevron" w={13} c="var(--faint)" />
    </button>
  );
}

window.Dashboard = Dashboard;
