// ============ Phase 4 — Business Memory: Business Events ============
// บันทึกเหตุการณ์สำคัญทางธุรกิจ เพื่อให้ AI เข้าใจ "ทำไม" ผลลัพธ์ถึงเปลี่ยน

const BE_TYPES = [
  { value: 'price_change',    label: 'เปลี่ยนราคาขาย',        tone: 'blue'   },
  { value: 'recipe_change',   label: 'เปลี่ยนสูตร/วัตถุดิบ',  tone: 'purple' },
  { value: 'promotion',       label: 'โปรโมชัน',               tone: 'green'  },
  { value: 'supplier_change', label: 'เปลี่ยนซัพพลายเออร์',   tone: 'orange' },
  { value: 'cost_change',     label: 'ต้นทุนเปลี่ยน',          tone: 'orange' },
  { value: 'staff_change',    label: 'เปลี่ยนแปลงพนักงาน',     tone: 'gray'   },
  { value: 'other',           label: 'อื่นๆ',                   tone: 'gray'   },
];

const BE_IMPACTS = [
  { value: 'positive', label: '+ ผลบวก',  tone: 'green'  },
  { value: 'negative', label: '− ผลลบ',   tone: 'red'    },
  { value: 'neutral',  label: '○ กลางๆ',  tone: 'gray'   },
];

function beTypeOf(v) { return BE_TYPES.find(t => t.value === v) || BE_TYPES[BE_TYPES.length - 1]; }
function beImpactOf(v) { return BE_IMPACTS.find(i => i.value === v) || BE_IMPACTS[2]; }

function newBEForm() {
  return {
    id: 'BEV' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
    type: 'other',
    date: new Date().toISOString().slice(0, 10),
    title: '',
    description: '',
    impact: 'neutral',
    linkedMenuId: '',
    linkedIngId: '',
    createdAt: new Date().toISOString(),
  };
}

function BusinessEventsPage() {
  const { fdb: db, setDb, logActivity, flash, settings } = useData();
  const isTh = settings.uiLang !== 'en';
  const [tab, setTab] = React.useState('log');
  const [form, setForm] = React.useState(newBEForm);
  const [filterType, setFilterType] = React.useState('all');

  const events = (db.businessEvents || []).slice().sort((a, b) => String(b.date).localeCompare(String(a.date)));
  const filtered = filterType === 'all' ? events : events.filter(e => e.type === filterType);
  const topType = BE_TYPES.map(t => ({ ...t, count: events.filter(e => e.type === t.value).length }))
    .filter(t => t.count > 0).sort((a, b) => b.count - a.count)[0];

  function save() {
    if (!form.title.trim()) { flash(isTh ? 'กรอกชื่อเหตุการณ์' : 'Enter event title', 'err'); return; }
    if (!form.date) { flash(isTh ? 'เลือกวันที่' : 'Select date', 'err'); return; }
    const ev = { ...form, createdAt: new Date().toISOString() };
    setDb(prev => ({ ...prev, businessEvents: [ev, ...(prev.businessEvents || [])] }));
    logActivity('business_event.created', { entityType: 'businessEvents', entityId: ev.id, note: ev.title });
    flash(isTh ? 'บันทึกเหตุการณ์แล้ว' : 'Event saved');
    setForm(newBEForm());
    setTab('history');
  }

  function del(ev) {
    if (!confirm(isTh ? `ลบเหตุการณ์ "${ev.title}"?` : `Delete "${ev.title}"?`)) return;
    setDb(prev => ({ ...prev, businessEvents: (prev.businessEvents || []).filter(e => e.id !== ev.id) }));
    logActivity('business_event.deleted', { entityType: 'businessEvents', entityId: ev.id, note: ev.title });
    flash(isTh ? 'ลบแล้ว' : 'Deleted');
  }

  const typeChips = <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
    {BE_TYPES.map(t =>
      <button key={t.value} onClick={() => setForm(f => ({ ...f, type: t.value }))}
        style={{ padding: '7px 14px', borderRadius: 9, fontSize: 13.5, fontWeight: 600, cursor: 'pointer',
          background: form.type === t.value ? 'var(--accent)' : 'var(--chip)',
          color: form.type === t.value ? '#fff' : 'var(--ink)', border: 'none', transition: 'background .15s' }}>
        {t.label}
      </button>)}
  </div>;

  return (
    <div className="view-enter" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14 }} className="r-2col">
        <Stat
          label={isTh ? 'เหตุการณ์ทั้งหมด' : 'Total events'}
          value={fmt(events.length)}
          icon="calendar"
          sub={isTh ? 'ความทรงจำธุรกิจ' : 'Business memory'} />
        <Stat
          label={isTh ? 'ล่าสุด' : 'Latest'}
          value={events[0] ? fmtDate(events[0].date) : '–'}
          icon="doc"
          sub={events[0] ? beTypeOf(events[0].type).label : (isTh ? 'ยังไม่มี' : 'None yet')} />
        <Stat
          label={isTh ? 'ประเภทที่บ่อยสุด' : 'Most common'}
          value={topType ? topType.label : '–'}
          icon="chart"
          sub={topType ? `${topType.count} ${isTh ? 'ครั้ง' : 'times'}` : ''} />
      </div>

      {/* Main card */}
      <Card>
        {/* Tabs */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
          {[
            { id: 'log',     label: isTh ? '+ บันทึกใหม่' : '+ New event' },
            { id: 'history', label: isTh ? `ประวัติ (${events.length})` : `History (${events.length})` },
          ].map(t =>
            <button key={t.id} onClick={() => setTab(t.id)}
              style={{ padding: '8px 18px', borderRadius: 9, fontWeight: 600, fontSize: 14, cursor: 'pointer', border: 'none',
                background: tab === t.id ? 'var(--accent)' : 'var(--chip)',
                color: tab === t.id ? '#fff' : 'var(--ink)' }}>
              {t.label}
            </button>)}
        </div>

        {tab === 'log' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 660 }}>

            <Field label={isTh ? 'ประเภทเหตุการณ์' : 'Event type'}>
              {typeChips}
            </Field>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Field label={isTh ? 'วันที่เกิดเหตุการณ์' : 'Event date'}>
                <Input type="date" value={form.date} onChange={e => setForm(f => ({ ...f, date: e.target.value }))} />
              </Field>
              <Field label={isTh ? 'ผลกระทบที่คาดหวัง' : 'Expected impact'}>
                <Select
                  value={form.impact}
                  onChange={e => setForm(f => ({ ...f, impact: e.target.value }))}
                  options={BE_IMPACTS.map(i => ({ value: i.value, label: i.label }))} />
              </Field>
            </div>

            <Field
              label={isTh ? 'ชื่อเหตุการณ์ (สั้นๆ)' : 'Event title (brief)'}
              hint={isTh ? 'เช่น "ขึ้นราคาอเมริกาโน่ 5 บาท" หรือ "เปลี่ยนมาใช้นม Oatly"' : 'e.g. "Raised Americano price 5 THB" or "Switched to Oatly milk"'}>
              <Input
                autoFocus
                value={form.title}
                placeholder={isTh ? 'กรอกชื่อเหตุการณ์...' : 'Event title...'}
                onChange={e => setForm(f => ({ ...f, title: e.target.value }))} />
            </Field>

            <Field label={isTh ? 'รายละเอียดเพิ่มเติม (ไม่บังคับ)' : 'Details (optional)'}>
              <textarea
                value={form.description}
                onChange={e => setForm(f => ({ ...f, description: e.target.value }))}
                placeholder={isTh
                  ? 'เหตุผล สิ่งที่คาดหวัง หรือสิ่งที่สังเกตเห็น...'
                  : 'Reasons, expected outcome, or observations...'}
                style={{
                  width: '100%', minHeight: 84, resize: 'vertical',
                  padding: '10px 12px', borderRadius: 10, border: '1px solid var(--line)',
                  fontSize: 14, background: 'var(--surface)', color: 'var(--ink)',
                  lineHeight: 1.6, fontFamily: 'inherit', boxSizing: 'border-box'
                }} />
            </Field>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Field label={isTh ? 'เมนูที่เกี่ยวข้อง (ไม่บังคับ)' : 'Related menu (optional)'}>
                <Select
                  value={form.linkedMenuId}
                  onChange={e => setForm(f => ({ ...f, linkedMenuId: e.target.value }))}
                  options={[
                    { value: '', label: isTh ? '— ไม่ระบุ —' : '— none —' },
                    ...db.menus.map(m => ({ value: m.id, label: `${m.name}` }))
                  ]} />
              </Field>
              <Field label={isTh ? 'วัตถุดิบที่เกี่ยวข้อง (ไม่บังคับ)' : 'Related ingredient (optional)'}>
                <Select
                  value={form.linkedIngId}
                  onChange={e => setForm(f => ({ ...f, linkedIngId: e.target.value }))}
                  options={[
                    { value: '', label: isTh ? '— ไม่ระบุ —' : '— none —' },
                    ...db.ingredients.map(i => ({ value: i.id, label: `${i.name}` }))
                  ]} />
              </Field>
            </div>

            <div style={{ display: 'flex', gap: 10 }}>
              <Button onClick={save} icon="check">
                {isTh ? 'บันทึกเหตุการณ์' : 'Save event'}
              </Button>
              <Button variant="secondary" onClick={() => setForm(newBEForm())}>
                {isTh ? 'ล้างแบบฟอร์ม' : 'Clear'}
              </Button>
            </div>
          </div>
        )}

        {tab === 'history' && (
          <div>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 16, flexWrap: 'wrap' }}>
              <div style={{ minWidth: 220 }}>
                <Select
                  value={filterType}
                  onChange={e => setFilterType(e.target.value)}
                  options={[
                    { value: 'all', label: isTh ? 'ทุกประเภท' : 'All types' },
                    ...BE_TYPES.map(t => ({ value: t.value, label: t.label }))
                  ]} />
              </div>
              <Badge tone="gray">{filtered.length} {isTh ? 'รายการ' : 'events'}</Badge>
            </div>

            {filtered.length ? (
              <div style={{ overflowX: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5, minWidth: 620 }}>
                  <thead>
                    <tr style={{ color: 'var(--ink-3)', borderBottom: '1px solid var(--line)', fontSize: 12 }}>
                      <th style={{ textAlign: 'left', padding: '10px 12px', fontWeight: 600 }}>{isTh ? 'วันที่' : 'Date'}</th>
                      <th style={{ textAlign: 'left', padding: '10px 12px', fontWeight: 600 }}>{isTh ? 'ประเภท' : 'Type'}</th>
                      <th style={{ textAlign: 'left', padding: '10px 12px', fontWeight: 600 }}>{isTh ? 'เหตุการณ์' : 'Event'}</th>
                      <th style={{ textAlign: 'left', padding: '10px 12px', fontWeight: 600 }}>{isTh ? 'ผล' : 'Impact'}</th>
                      <th style={{ textAlign: 'left', padding: '10px 12px', fontWeight: 600 }}>{isTh ? 'เชื่อมกับ' : 'Linked'}</th>
                      <th style={{ width: 40 }} />
                    </tr>
                  </thead>
                  <tbody>
                    {filtered.map(ev => {
                      const t = beTypeOf(ev.type);
                      const imp = beImpactOf(ev.impact);
                      const menu = ev.linkedMenuId ? db.menus.find(m => m.id === ev.linkedMenuId) : null;
                      const ing = ev.linkedIngId ? db.ingredients.find(i => i.id === ev.linkedIngId) : null;
                      return (
                        <tr key={ev.id} style={{ borderBottom: '1px solid var(--line-2)' }}>
                          <td style={{ padding: '12px 12px', whiteSpace: 'nowrap', fontWeight: 600 }}>
                            {fmtDate(ev.date)}
                          </td>
                          <td style={{ padding: '12px 12px' }}>
                            <Badge tone={t.tone}>{t.label}</Badge>
                          </td>
                          <td style={{ padding: '12px 12px' }}>
                            <div style={{ fontWeight: 600 }}>{ev.title}</div>
                            {ev.description && (
                              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 3, lineHeight: 1.5 }}>
                                {ev.description}
                              </div>
                            )}
                          </td>
                          <td style={{ padding: '12px 12px' }}>
                            <Badge tone={imp.tone}>{imp.label}</Badge>
                          </td>
                          <td style={{ padding: '12px 12px', fontSize: 13, color: 'var(--ink-2)' }}>
                            {menu && <div>{menu.name}</div>}
                            {ing && <div>{ing.name}</div>}
                            {!menu && !ing && <span style={{ color: 'var(--ink-3)' }}>–</span>}
                          </td>
                          <td style={{ padding: '12px 8px' }}>
                            <button
                              onClick={() => del(ev)}
                              title={isTh ? 'ลบ' : 'Delete'}
                              style={{ padding: '5px 10px', borderRadius: 7, fontSize: 12, fontWeight: 600,
                                color: 'var(--red)', background: 'transparent', border: 'none', cursor: 'pointer' }}>
                              {isTh ? 'ลบ' : 'Del'}
                            </button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            ) : (
              <Empty
                icon="calendar"
                title={isTh ? 'ยังไม่มีเหตุการณ์' : 'No events yet'}
                sub={isTh
                  ? 'กดแท็บ "บันทึกใหม่" เพื่อบันทึกเหตุการณ์สำคัญ เช่น ขึ้นราคา เปลี่ยนสูตร หรือเริ่มโปรโมชัน'
                  : 'Go to "New event" to log important changes like price raises, recipe updates, or promotions'}
              />
            )}
          </div>
        )}
      </Card>

      {/* AI context hint */}
      <div style={{
        display: 'flex', gap: 14, alignItems: 'flex-start',
        background: 'var(--accent-soft)', borderRadius: 14, padding: '16px 18px'
      }}>
        <Icon name="chart" size={22} color="var(--accent)" style={{ flexShrink: 0, marginTop: 2 }} />
        <div>
          <div style={{ fontWeight: 700, color: 'var(--accent)', marginBottom: 5, fontSize: 14.5 }}>
            {isTh ? 'ทำไมต้องบันทึกเหตุการณ์?' : 'Why log business events?'}
          </div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.75 }}>
            {isTh
              ? 'AI ไม่รู้ว่า "ทำไม" กำไรถึงลด หรือทำไมยอดขายถึงพุ่ง — แต่ถ้าคุณบันทึกไว้ว่า "วันนั้นขึ้นราคา" หรือ "เดือนนี้ทำโปรโมชัน" AI จะเชื่อมผลลัพธ์กับเหตุการณ์ได้จริง ไม่ใช่แค่สมมติฐาน'
              : 'AI cannot know "why" profits dropped or sales jumped — but if you log "we raised prices that day" or "ran a promotion this month," the AI Advisor can connect outcomes to real events, not guesses.'}
          </div>
        </div>
      </div>

    </div>
  );
}

Object.assign(window, { BusinessEventsPage });
