// ─── Customer Journey — unified timeline of all entries ──────
// Activities (with timestamps), kiki comments, opportunity milestones,
// quote events — merged chronologically, optional per-customer filter.

function journeyAccountOf(refType, refId) {
  if (!refId) return null;
  if (refType === 'account') return refId;
  if (refType === 'opportunity') { const o = CRMStore.get('opportunities', refId); return o ? o.accountId : null; }
  if (refType === 'quote') { const q = CRMStore.get('quotes', refId); return q ? q.accountId : null; }
  return null;
}

function buildJourney() {
  const ev = [];
  const push = (e) => { if (e.dt && !isNaN(e.dt)) ev.push(e); };

  // Activities
  CRMStore.list('activities').forEach(a => {
    push({ dt: parseWhen(a.when), type: 'activity', kind: a.kind, icon: (ACT_KIND[a.kind] || {}).ico || 'activities',
      title: a.subject, sub: (ACT_KIND[a.kind] || {}).label + (a.done ? ' · erledigt' : ''),
      refType: a.refType, refId: a.refId, owner: a.owner, done: a.done });
  });
  // kiki comments
  KikiStore.list.forEach(c => {
    const refType = c.kind === 'Account' ? 'account' : c.kind === 'Opportunity' ? 'opportunity' : c.kind === 'Quote' ? 'quote' : c.kind === 'Lead' ? 'lead' : 'other';
    push({ dt: new Date(c.ts), type: 'comment', icon: 'comment', cat: c.cat,
      title: c.text, sub: 'kiki · ' + c.cat + ' · ' + (c.refLabel || c.refId),
      refType: refType, refId: c.refId, owner: 'JS' });
  });
  // Opportunity milestones
  CRMStore.list('opportunities').forEach(o => {
    push({ dt: new Date(o.createdAt), type: 'opp', icon: 'opps', title: 'Opportunity angelegt: ' + o.name,
      sub: fmtEUR(o.amount) + ' · ' + (STAGE_META[o.stage] || {}).label, refType: 'opportunity', refId: o.id, owner: o.owner });
    if (o.stage === 'won' || o.stage === 'lost') {
      push({ dt: new Date(o.close || o.createdAt), type: o.stage === 'won' ? 'won' : 'lost', icon: o.stage === 'won' ? 'target' : 'opps',
        title: (o.stage === 'won' ? 'Gewonnen: ' : 'Verloren: ') + o.name,
        sub: fmtEUR(o.amount) + (o.stage === 'lost' && o.competitor ? ' · an ' + o.competitor + (o.lossReason ? ' (' + (LOSS_REASON[o.lossReason] || o.lossReason) + ')' : '') : ''),
        refType: 'opportunity', refId: o.id, owner: o.owner });
    }
  });
  // Quote events
  CRMStore.list('quotes').forEach(q => {
    push({ dt: new Date(q.createdAt), type: 'quote', icon: 'quotes', title: 'Angebot erstellt: ' + q.title,
      sub: fmtEUR(quoteTotal(q)) + ' · ' + (QUOTE_STATUS[q.status] || {}).label, refType: 'quote', refId: q.id, owner: q.owner });
  });
  // Attachments (mails / documents)
  CRMStore.list('attachments').forEach(a => {
    push({ dt: parseWhen(a.when), type: 'attach', icon: a.atype === 'mail' ? 'mail' : 'file',
      title: (a.atype === 'mail' ? 'E-Mail: ' : 'Dokument: ') + a.name,
      sub: (a.from ? a.from + ' · ' : '') + (a.note || ''), refType: a.refType, refId: a.refId, owner: a.owner });
  });
  // SAP events (orders / zANF)
  CRMStore.list('saporders').forEach(o => {
    push({ dt: new Date(o.when), type: 'sap', icon: 'plug',
      title: (o.kind === 'zanf' ? 'SAP-zANF: ' : 'SAP-Auftrag: ') + o.sapNo,
      sub: o.desc + ' · ' + o.status, refType: o.oppId ? 'opportunity' : 'account', refId: o.oppId || o.accountId, owner: 'JS' });
  });

  ev.sort((a, b) => b.dt - a.dt);
  return ev;
}

const JTYPE = {
  activity: { dot: 'var(--accent)' },
  comment:  { dot: '#6f57c4' },
  opp:      { dot: 'var(--muted-2)' },
  won:      { dot: 'var(--success)' },
  lost:     { dot: 'var(--danger)' },
  quote:    { dot: '#B5944E' },
  attach:   { dot: '#3E8E7E' },
  sap:      { dot: '#2A6FB0' }
};
const JTYPE_LABEL = { activity:'Aktivität', comment:'kiki-Kommentar', opp:'Opportunity', won:'Gewonnen', lost:'Verloren', quote:'Angebot', attach:'Anhang', sap:'SAP' };

function CustomerJourneyView() {
  useKiki();
  const [acc, setAcc] = useS('all');
  const [owner, setOwner] = useS('all');
  const [types, setTypes] = useS({ activity:true, comment:true, opp:true, won:true, lost:true, quote:true, attach:true, sap:true });

  const accounts = CRMStore.list('accounts');
  let ev = scopeOwner(buildJourney());
  if (acc !== 'all') {
    if (acc.indexOf('LED') === 0) ev = ev.filter(e => e.refType === 'lead' && e.refId === acc);
    else ev = ev.filter(e => journeyAccountOf(e.refType, e.refId) === acc);
  }
  if (owner !== 'all') ev = ev.filter(e => e.owner === owner);
  ev = ev.filter(e => types[e.type]);

  // group by day
  const groups = [];
  let cur = null;
  ev.forEach(e => {
    const day = e.dt.toLocaleDateString('de-DE', { weekday: 'long', day: '2-digit', month: 'long', year: 'numeric' });
    if (!cur || cur.day !== day) { cur = { day, items: [] }; groups.push(cur); }
    cur.items.push(e);
  });

  const accName = (id) => { const a = CRMStore.get('accounts', id); return a ? a.name : id; };
  const refLabelJ = (e) => {
    if (e.refType === 'opportunity') { const o = CRMStore.get('opportunities', e.refId); return o ? o.name : e.refId; }
    if (e.refType === 'account') return accName(e.refId);
    if (e.refType === 'quote') { const q = CRMStore.get('quotes', e.refId); return q ? q.title : e.refId; }
    if (e.refType === 'lead') { const l = CRMStore.get('leads', e.refId); return l ? l.company : e.refId; }
    return '';
  };

  const TYPE_FILTERS = [['activity','Aktivitäten'],['comment','kiki-Kommentare'],['attach','Anhänge'],['sap','SAP'],['opp','Opportunities'],['won','Gewonnen'],['lost','Verloren'],['quote','Angebote']];

  return (
    <div className="page">
      <div className="page-title-row">
        <div>
          <h1 className="page-title">Customer Journey</h1>
          <p className="page-sub">Alle Aktivitäten, Meilensteine und kiki-Kommentare auf einem Zeitstrahl — mit Zeitstempel. Rechtsklick auf einen Eintrag fügt einen Kommentar hinzu.</p>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <select className="form-select" style={{ width: 240 }} value={acc} onChange={e => setAcc(e.target.value)}>
            <option value="all">Alle Kunden &amp; Leads</option>
            <optgroup label="Kunden">
              {accounts.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
            </optgroup>
            <optgroup label="Leads">
              {CRMStore.list('leads').map(l => <option key={l.id} value={l.id}>{l.company}</option>)}
            </optgroup>
          </select>
          <select className="form-select" style={{ width: 180 }} value={owner} onChange={e => setOwner(e.target.value)}>
            <option value="all">Alle Owner</option>
            {OWNER_OPTS.map(o => <option key={o[0]} value={o[0]}>{o[1]}</option>)}
          </select>
        </div>
      </div>

      <div className="jrny-filters">
        {TYPE_FILTERS.map(t => (
          <label key={t[0]} className={"jrny-filter" + (types[t[0]] ? ' on' : '')}>
            <input type="checkbox" checked={types[t[0]]} onChange={() => setTypes(p => ({ ...p, [t[0]]: !p[t[0]] }))} />
            <span className="jrny-dot" style={{ background: JTYPE[t[0]].dot }}></span>{t[1]}
          </label>
        ))}
        <span className="jrny-count">{ev.length} Einträge</span>
      </div>

      <div className="lv-card" style={{ padding: '8px 0' }}>
        {groups.length === 0 ? <div className="empty">Keine Einträge für diese Auswahl.</div> :
          <div className="jrny">
            {groups.map((g, gi) => (
              <div key={gi} className="jrny-group">
                <div className="jrny-day">{g.day}</div>
                {g.items.map((e, i) => (
                  <div key={i} className="jrny-item" data-kiki-id={e.refId || ('ev-' + gi + '-' + i)} data-kiki-label={e.title.slice(0, 50)} data-kiki-kind={JTYPE_LABEL[e.type]}>
                    <div className="jrny-rail"><span className="jrny-node" style={{ background: JTYPE[e.type].dot }}>{e.type === 'comment' ? '' : ''}</span></div>
                    <div className="jrny-card">
                      <div className="jrny-card-hd">
                        <span className="jrny-ic" style={{ color: JTYPE[e.type].dot }}>{e.type === 'comment' ? <span className="kiki-badge-sm">ki</span> : Icons[e.icon]}</span>
                        <b className={e.done ? 'done' : ''}>{e.title}</b>
                        <span className="jrny-time">{e.dt.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })}</span>
                      </div>
                      <div className="jrny-meta">
                        <span className="jrny-tag" style={{ color: JTYPE[e.type].dot, borderColor: JTYPE[e.type].dot }}>{JTYPE_LABEL[e.type]}</span>
                        {e.sub && <span>{e.sub}</span>}
                        {refLabelJ(e) && <span className="jrny-ref">· {refLabelJ(e)}</span>}
                        {e.owner && <span className="jrny-owner">{e.owner}</span>}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ))}
          </div>
        }
      </div>
    </div>
  );
}
