// Log — daily conversation log.
// Each day's user + AI messages grouped as one conversation card.
// Tapping a card opens the full thread view.

const logStyles = {
  scroll: { height: '100%', overflow: 'auto', direction: 'rtl' },

  filterRow: {
    display: 'flex', gap: 6, overflowX: 'auto',
    padding: '12px 0 8px', scrollbarWidth: 'none',
  },
  chip: {
    flex: 'none',
    font: "500 12px 'Estedad', sans-serif",
    padding: '7px 13px', borderRadius: 999,
    background: 'var(--paper-2)', color: 'var(--ink-2)',
    border: '1px solid rgba(27,26,23,0.06)',
    cursor: 'pointer',
    display: 'inline-flex', alignItems: 'center', gap: 6,
  },
  chipActive: { background: 'var(--ink)', color: 'var(--paper)', borderColor: 'transparent' },

  convCard: {
    background: 'var(--surface)',
    border: '1px solid rgba(27,26,23,0.06)',
    borderRadius: 16, padding: '14px 16px',
    boxShadow: 'var(--shadow-lift)',
    cursor: 'pointer', marginBottom: 12,
  },
  convHead: {
    display: 'flex', alignItems: 'center', gap: 8,
    marginBottom: 8,
  },
  datePill: {
    flex: 1,
    font: "600 14px 'Estedad', sans-serif",
    color: 'var(--ink)',
  },
  convCount: {
    font: "500 11px 'Estedad', sans-serif",
    color: 'var(--ink-3)',
    background: 'var(--paper-2)',
    padding: '3px 8px', borderRadius: 999,
  },
  starBtn: {
    background: 'transparent', border: 'none', cursor: 'pointer',
    color: 'var(--ink-4)', padding: 2,
    display: 'grid', placeItems: 'center',
  },
  starOn: { color: 'var(--saffron)' },

  convMeta: {
    display: 'flex', alignItems: 'center', gap: 5,
    marginBottom: 8,
    font: "400 11px 'Estedad', sans-serif", color: 'var(--ink-3)',
  },
  convPreview: {
    font: "400 14px/1.6 'Estedad', sans-serif",
    color: 'var(--ink-2)',
    display: '-webkit-box',
    WebkitLineClamp: 2,
    WebkitBoxOrient: 'vertical',
    overflow: 'hidden',
    direction: 'rtl', textAlign: 'right',
    marginBottom: 8,
  },
  extracted: { display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 4 },
  extractTag: {
    display: 'inline-flex', alignItems: 'center', gap: 4,
    font: "500 10.5px 'Estedad', sans-serif",
    padding: '3px 8px', borderRadius: 999,
  },
  extractTask:      { background: 'var(--firoozeh-soft)', color: 'var(--firoozeh-deep)' },
  extractKnowledge: { background: 'var(--saffron-soft)',  color: 'var(--saffron)' },
  navArrow: {
    display: 'flex', justifyContent: 'flex-end',
    color: 'var(--ink-4)',
  },

  empty: {
    padding: '60px 16px', textAlign: 'center', direction: 'rtl',
    color: 'var(--ink-3)', font: "400 15px 'Estedad', sans-serif",
  },

  // ── Detail / thread view ──────────────────────────────────────
  detail: {
    height: '100%', display: 'flex', flexDirection: 'column',
    overflow: 'hidden', direction: 'rtl',
  },
  detailHeader: {
    display: 'flex', alignItems: 'center', gap: 8,
    padding: '12px 14px',
    borderBottom: '1px solid rgba(27,26,23,0.08)',
    flexShrink: 0,
  },
  backBtn: {
    background: 'none', border: 'none', cursor: 'pointer',
    color: 'var(--firoozeh)', padding: '4px 2px 4px 8px',
    display: 'grid', placeItems: 'center',
  },
  detailScroll: { flex: 1, overflow: 'auto', padding: '16px 16px 120px' },

  msgWrap: { display: 'flex', marginBottom: 14 },
  msgWrapUser: { justifyContent: 'flex-start' },   // RTL: start = right
  msgWrapAI:   { justifyContent: 'flex-end' },     // RTL: end = left

  bubbleUser: {
    maxWidth: '82%',
    background: 'var(--firoozeh)',
    color: '#fff',
    borderRadius: 16, borderTopRightRadius: 4,
    padding: '10px 14px',
  },
  bubbleAI: {
    maxWidth: '82%',
    background: 'var(--surface)',
    border: '1px solid rgba(27,26,23,0.08)',
    color: 'var(--ink)',
    borderRadius: 16, borderTopLeftRadius: 4,
    padding: '10px 14px',
  },
  bubbleText: {
    font: "400 15px/1.7 'Estedad', sans-serif",
    direction: 'rtl', textAlign: 'right',
    whiteSpace: 'pre-wrap',
  },
  bubbleTime: {
    font: "400 10px 'Estedad', sans-serif",
    marginTop: 5, textAlign: 'left', direction: 'ltr',
    opacity: 0.6,
  },
  voiceChip: {
    display: 'inline-flex', alignItems: 'center', gap: 4,
    font: "500 10px 'Estedad', sans-serif",
    padding: '2px 7px', borderRadius: 999,
    background: 'rgba(255,255,255,0.22)',
    marginBottom: 6,
  },
  bubbleTags: { display: 'flex', gap: 4, flexWrap: 'wrap', marginTop: 8 },
  bubbleTag: {
    display: 'inline-flex', alignItems: 'center', gap: 3,
    font: "500 10px 'Estedad', sans-serif",
    padding: '2px 7px', borderRadius: 999,
    background: 'rgba(255,255,255,0.25)',
    color: '#fff',
  },

  deleteBtn: {
    width: '100%', padding: '13px',
    background: 'rgba(180,30,30,0.06)',
    border: '1px solid rgba(180,30,30,0.15)',
    borderRadius: 12, cursor: 'pointer',
    font: "500 14px 'Estedad', sans-serif",
    color: '#B41E1E',
    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    direction: 'rtl', marginTop: 16,
  },
  exportBtn: {
    flex: 1, padding: '12px',
    background: 'var(--firoozeh-soft)',
    border: '1px solid rgba(42,157,143,0.18)',
    borderRadius: 12, cursor: 'pointer',
    font: "500 14px 'Estedad', sans-serif",
    color: 'var(--firoozeh-deep)',
    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    direction: 'rtl',
  },

  searchWrap: {
    display: 'flex', alignItems: 'center', gap: 8,
    background: 'var(--surface)', border: '1px solid rgba(27,26,23,0.08)',
    borderRadius: 12, padding: '10px 14px', margin: '12px 0 4px',
    color: 'var(--ink-3)',
  },
  searchInput: {
    flex: 1, border: 'none', outline: 'none', background: 'transparent',
    font: "400 14px 'Estedad', sans-serif", color: 'var(--ink)',
    direction: 'rtl', textAlign: 'right',
  },
};

const faTimeFmt = new Intl.DateTimeFormat('fa-IR', { hour: '2-digit', minute: '2-digit' });
const toFaLog = n => String(n).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);

const getMsgTime = m =>
  m.timestamp ? faTimeFmt.format(new Date(m.timestamp)) : (m.time || '');

// ── Export helpers ───────────────────────────────────────────────
const _convToText = conv => {
  const lines = [conv.dateLabel || '', ''];
  conv.messages.forEach(m => {
    const who = m.role === 'user' ? 'من' : 'دستیار';
    lines.push(`[${who} · ${getMsgTime(m)}] ${m.text || ''}`);
  });
  return lines.join('\n');
};

const _downloadText = conv => {
  const blob = new Blob([_convToText(conv)], { type: 'text/plain;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `logi-${conv.dateKey || conv.id}.txt`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const _printPDF = conv => {
  const w = window.open('', '_blank');
  if (!w) return;
  const esc = s => String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  const rows = conv.messages.map(m => {
    const who = m.role === 'user' ? 'من' : 'دستیار';
    return `<div class="msg ${m.role}"><div class="who">${esc(who)} · ${esc(getMsgTime(m))}</div><div class="txt">${esc(m.text)}</div></div>`;
  }).join('');
  w.document.write(`<!doctype html><html lang="fa" dir="rtl"><head><meta charset="utf-8"><title>${esc(conv.dateLabel)}</title>
<style>
  body { font-family: 'Estedad', Tahoma, sans-serif; margin: 32px; color: #191C1D; }
  h1 { font-size: 20px; border-bottom: 2px solid #2A9D8F; padding-bottom: 10px; }
  .msg { margin: 0 0 14px; padding: 10px 14px; border-radius: 12px; max-width: 80%; }
  .msg.user { background: #DDF3F0; margin-inline-start: auto; }
  .msg.assistant { background: #F3F4F5; margin-inline-end: auto; }
  .who { font-size: 11px; color: #6D7A77; margin-bottom: 4px; }
  .txt { font-size: 14px; line-height: 1.8; white-space: pre-wrap; }
  @media print { body { margin: 12px; } }
</style></head><body><h1>${esc(conv.dateLabel)}</h1>${rows}
<script>window.onload=function(){window.print();}</script></body></html>`);
  w.document.close();
};

// ── Full thread / conversation detail ────────────────────────────
function ConvDetail({ conv, onBack, onStar, onDelete }) {
  const { Icons } = window;
  return (
    <div style={logStyles.detail}>
      <div style={logStyles.detailHeader}>
        <button style={logStyles.backBtn} onClick={onBack} aria-label="بازگشت">
          <Icons.Chev size={24} />
        </button>
        <span style={{ font: "600 16px 'Estedad', sans-serif", color: 'var(--ink)', flex: 1 }}>
          {conv.dateLabel}
        </span>
        <button
          style={{ ...logStyles.starBtn, ...(conv.starred ? logStyles.starOn : {}) }}
          onClick={() => onStar(conv.id)}
          aria-label="ستاره"
        >
          {conv.starred ? <Icons.StarFill size={20} /> : <Icons.Star size={20} />}
        </button>
      </div>

      <div style={logStyles.detailScroll}>
        {conv.messages.map(msg => {
          const isUser = msg.role === 'user';
          return (
            <div key={msg.id} style={{
              ...logStyles.msgWrap,
              ...(isUser ? logStyles.msgWrapUser : logStyles.msgWrapAI),
            }}>
              <div style={isUser ? logStyles.bubbleUser : logStyles.bubbleAI}>
                {isUser && msg.kind === 'voice' && (
                  <div style={logStyles.voiceChip}>
                    <Icons.Mic size={10} />
                    {msg.dur ? `صدا · ${msg.dur}` : 'صدا'}
                  </div>
                )}
                <div style={logStyles.bubbleText}>{msg.text}</div>
                <div style={logStyles.bubbleTime}>{getMsgTime(msg)}</div>
                {isUser && msg.extracted?.length > 0 && (
                  <div style={logStyles.bubbleTags}>
                    {msg.extracted.map((t, i) => (
                      <span key={i} style={logStyles.bubbleTag}>
                        <Icons.CheckCircle size={10} />
                        {t.label}
                      </span>
                    ))}
                  </div>
                )}
              </div>
            </div>
          );
        })}

        <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
          <button style={logStyles.exportBtn} onClick={() => _downloadText(conv)}>
            <Icons.Doc size={15} /> متن
          </button>
          <button style={logStyles.exportBtn} onClick={() => _printPDF(conv)}>
            <Icons.Doc size={15} /> PDF
          </button>
        </div>

        <button style={logStyles.deleteBtn} onClick={() => (window.confirmAction || ((m, f) => f()))('این مکالمه حذف شود؟', () => onDelete(conv.id))}>
          <Icons.Trash size={16} />
          حذف این مکالمه
        </button>
      </div>
    </div>
  );
}

// ── Conversation card (list item) ────────────────────────────────
function ConvCard({ conv, onOpen, onStar }) {
  const { Icons } = window;

  const userMsgs = conv.messages.filter(m => m.role === 'user');
  const lastUserMsg = userMsgs[userMsgs.length - 1];
  const lastTime = conv.lastTimestamp
    ? faTimeFmt.format(new Date(conv.lastTimestamp))
    : (lastUserMsg?.time || '');
  const allExtracted = userMsgs.flatMap(m => m.extracted || []);
  const hasVoice = userMsgs.some(m => m.kind === 'voice');
  const hasText  = userMsgs.some(m => m.kind !== 'voice');

  return (
    <div style={logStyles.convCard} onClick={() => onOpen(conv.id)}>
      <div style={logStyles.convHead}>
        <span style={logStyles.datePill}>{conv.dateLabel}</span>
        <span style={logStyles.convCount}>{toFaLog(userMsgs.length)} ورودی</span>
        <button
          style={{ ...logStyles.starBtn, ...(conv.starred ? logStyles.starOn : {}) }}
          onClick={e => { e.stopPropagation(); onStar(conv.id); }}
          aria-label="ستاره"
        >
          {conv.starred ? <Icons.StarFill size={15} /> : <Icons.Star size={15} />}
        </button>
      </div>

      <div style={logStyles.convMeta}>
        {hasVoice && <><Icons.Mic size={11} /> صدا</>}
        {hasVoice && hasText && <span style={{ opacity: 0.4 }}>·</span>}
        {hasText  && <><Icons.Type size={11} /> متن</>}
        <span style={{ opacity: 0.4 }}>·</span>
        <span>{lastTime}</span>
      </div>

      {lastUserMsg && (
        <div style={logStyles.convPreview}>{lastUserMsg.text}</div>
      )}

      {allExtracted.length > 0 && (
        <div style={logStyles.extracted}>
          {allExtracted.slice(0, 4).map((t, i) => (
            <span key={i} style={{
              ...logStyles.extractTag,
              ...(t.kind === 'task' ? logStyles.extractTask : logStyles.extractKnowledge),
            }}>
              {t.kind === 'task' ? <Icons.CheckCircle size={11} /> : <Icons.Book size={11} />}
              {t.label}
            </span>
          ))}
          {allExtracted.length > 4 && (
            <span style={{ ...logStyles.extractTag, background: 'var(--paper-2)', color: 'var(--ink-3)' }}>
              +{toFaLog(allExtracted.length - 4)}
            </span>
          )}
        </div>
      )}

      <div style={logStyles.navArrow}>
        <Icons.ChevLeft size={14} />
      </div>
    </div>
  );
}

// ── Log screen ────────────────────────────────────────────────────
function Log({ conversations, onStar, onDelete, isDesktop, openConvId, onConvOpened }) {
  const { Icons } = window;
  const [filter, setFilter] = React.useState('all');
  const [q, setQ] = React.useState('');
  const [detail, setDetail] = React.useState(null);
  const [showCount, setShowCount] = React.useState(15);

  React.useEffect(() => {
    if (openConvId) {
      setDetail(openConvId);
      if (onConvOpened) onConvOpened();
    }
  }, [openConvId]);

  if (detail) {
    const conv = conversations.find(c => c.id === detail);
    if (!conv) { setDetail(null); return null; }
    return (
      <ConvDetail
        conv={conv}
        onBack={() => setDetail(null)}
        onStar={onStar}
        onDelete={id => { onDelete(id); setDetail(null); }}
      />
    );
  }

  const filterDefs = [
    { key: 'all',   label: 'همه',       Icon: Icons.Filter },
    { key: 'today', label: 'امروز',     Icon: Icons.Clock },
    { key: 'week',  label: 'این هفته',  Icon: Icons.Calendar },
    { key: 'month', label: 'این ماه',   Icon: Icons.Calendar },
    { key: 'star',  label: 'ستاره‌دار', Icon: Icons.Star },
  ];

  const now = new Date();
  const todayKey = [now.getFullYear(), String(now.getMonth()+1).padStart(2,'0'), String(now.getDate()).padStart(2,'0')].join('-');
  const monthKey = todayKey.slice(0, 7);
  const weekAgo = Date.now() - 7 * 86400000;
  const convDateKey = c => c.dateKey || (c.timestamp ? (() => { const d = new Date(c.timestamp); return [d.getFullYear(), String(d.getMonth()+1).padStart(2,'0'), String(d.getDate()).padStart(2,'0')].join('-'); })() : '');

  React.useEffect(() => { setShowCount(15); }, [filter, q]);

  const qWords = q.trim().toLowerCase().split(/\s+/).filter(Boolean);
  const filtered = conversations.filter(c => {
    if (filter === 'star')  { if (!c.starred) return false; }
    if (filter === 'today') { if (convDateKey(c) !== todayKey) return false; }
    if (filter === 'week')  { if (!((c.lastTimestamp || c.timestamp || 0) >= weekAgo)) return false; }
    if (filter === 'month') { if (convDateKey(c).slice(0, 7) !== monthKey) return false; }
    if (qWords.length > 0) {
      const hay = c.messages.map(m => m.text || '').join(' ').toLowerCase();
      if (!qWords.every(w => hay.includes(w))) return false;
    }
    return true;
  });

  const pad = isDesktop ? '0 24px 60px' : '0 16px 140px';

  return (
    <div style={{ ...logStyles.scroll, padding: pad }}>
      <div style={logStyles.searchWrap}>
        <Icons.Search size={18} />
        <input
          style={logStyles.searchInput}
          placeholder="جستجو در همه گفتگوها…"
          value={q}
          onChange={e => setQ(e.target.value)}
        />
        {q && (
          <button onClick={() => setQ('')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', padding: 2, display: 'grid', placeItems: 'center' }}>
            <Icons.X size={15} />
          </button>
        )}
      </div>

      <div style={logStyles.filterRow}>
        {filterDefs.map(f => {
          const active = filter === f.key;
          return (
            <button key={f.key}
              style={{ ...logStyles.chip, ...(active ? logStyles.chipActive : {}) }}
              onClick={() => setFilter(f.key)}
            >
              <f.Icon size={13} /> {f.label}
            </button>
          );
        })}
      </div>

      {qWords.length > 0 && (
        <div style={{ font: "400 12px 'Estedad', sans-serif", color: 'var(--ink-3)', margin: '4px 0 10px', direction: 'rtl' }}>
          {toFaLog(filtered.length)} نتیجه برای «{q}»
        </div>
      )}

      {filtered.length === 0 && (
        <div style={logStyles.empty}>
          <div style={{ fontSize: 36, marginBottom: 10 }}>{qWords.length > 0 ? '🔍' : '◎'}</div>
          <div>{qWords.length > 0 ? `نتیجه‌ای برای «${q}» پیدا نشد` : 'هنوز مکالمه‌ای اینجا نیست'}</div>
          {qWords.length === 0 && (
            <div style={{ fontSize: 12, marginTop: 6, color: 'var(--ink-4)' }}>
              هر چیزی که بنویسی یا بگی اینجا ثبت می‌شه
            </div>
          )}
        </div>
      )}

      {filtered.slice(0, showCount).map(conv => (
        <ConvCard
          key={conv.id}
          conv={conv}
          onOpen={setDetail}
          onStar={onStar}
        />
      ))}

      {filtered.length > showCount && (
        <button
          onClick={() => setShowCount(c => c + 15)}
          style={{
            display: 'block', width: '100%', margin: '8px 0 16px',
            padding: '12px', border: '1px solid rgba(27,26,23,0.10)',
            borderRadius: 14, background: 'var(--surface)',
            font: "500 14px 'Estedad', sans-serif",
            color: 'var(--ink-2)', cursor: 'pointer', direction: 'rtl',
          }}
        >
          مکالمات قدیمی‌تر ({String(filtered.length - showCount).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d])} مورد دیگر)
        </button>
      )}
    </div>
  );
}

window.Log = Log;
