// Home screen — V3 (Phase 3 refinement)
// Hero greeting + CoS Daily Brief + compact ask + hub + devam edenler

const greetingFor = (hour) => {
  if (hour >= 6 && hour < 12)  return 'Hayırlı sabahlar, Neşet.';
  if (hour >= 12 && hour < 17) return 'Hayırlı günler, Neşet.';
  if (hour >= 17 && hour < 22) return 'İyi akşamlar, Neşet.';
  return 'Geceniz hayırlı olsun, Neşet.';
};

const daypartFor = (hour) => {
  if (hour >= 6 && hour < 9)   return 'dawn';
  if (hour >= 9 && hour < 17)  return 'midday';
  if (hour >= 17 && hour < 20) return 'golden';
  return 'midnight';
};

const todayTR = () => {
  const days = ['Pazar','Pazartesi','Salı','Çarşamba','Perşembe','Cuma','Cumartesi'];
  const months = ['Ocak','Şubat','Mart','Nisan','Mayıs','Haziran','Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'];
  const d = new Date();
  return `${days[d.getDay()]} · ${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}`;
};

const SUGGESTIONS = [
  'Bugün dikkat etmem gereken bir şey var mı?',
  "KW Viya'da neden satışlar yavaşladı?",
  'Bu haftanın en kritik 3 kararı ne?',
];

const STOPLIGHT = { red: '🔴', amber: '🟡', green: '🟢' };

// --- Adapter: prod backend cosBrief (markdown string content) → Hero shape (top3 + content blocks) ---
// Prod cosBrief shape: { brief_date, content: 'markdown string', short_summary, tools_used: [], consult_targets: [], generated_at, trigger_type, ... }
// Hero shape: { ...same, content: [blocks], top3: [{title, detail, action, light}] }
function emojiToLight(s) {
  if (/🔴/.test(s)) return 'red';
  if (/🟢/.test(s)) return 'green';
  return 'amber';
}

function extractTop3FromMarkdown(md) {
  if (!md) return [];
  // Find "Top 3" section under heading like "## ⚡ Bugün Öne Çıkan" / "## Bugün Öne Çıkan (Top 3)"
  const lines = md.split('\n');
  let inTop3 = false;
  const items = [];
  let current = null;
  for (let i = 0; i < lines.length && items.length < 3; i++) {
    const l = lines[i];
    if (/^#{1,3}\s/.test(l)) {
      if (/öne çıkan|top\s*3/i.test(l)) {
        inTop3 = true;
        continue;
      }
      if (inTop3) break; // next heading ends section
    }
    if (!inTop3) continue;
    const numMatch = l.match(/^\s*(\d+)\.\s+(.+)$/);
    if (numMatch) {
      if (current) items.push(current);
      const raw = numMatch[2].replace(/\*\*/g, '').trim();
      const light = emojiToLight(raw);
      const title = raw.replace(/^[🔴🟡🟢]\s*/, '').replace(/[—–-].*$/, '').trim();
      const detail = (raw.match(/[—–-]\s*(.+)$/) || [, ''])[1].trim();
      current = { title, detail, action: '', light };
    } else if (current) {
      const actionMatch = l.match(/^\s*\*?\(action:?\s*(.+?)\)?\*?\s*$/i) || l.match(/action:\s*(.+)/i);
      if (actionMatch) current.action = actionMatch[1].trim();
      else if (!current.detail && l.trim()) current.detail = l.trim();
    }
  }
  if (current && items.length < 3) items.push(current);
  return items;
}

function markdownToBlocks(md) {
  if (!md) return [];
  const lines = md.split('\n');
  const blocks = [];
  let para = [];
  let listBuf = [];
  const flushPara = () => { if (para.length) { blocks.push({ type: 'p', text: para.join(' ') }); para = []; } };
  const flushList = () => { if (listBuf.length) { blocks.push({ type: 'ul', items: listBuf }); listBuf = []; } };
  for (const raw of lines) {
    const l = raw.trimEnd();
    if (!l.trim()) { flushPara(); flushList(); continue; }
    const h2 = l.match(/^##\s+(.+)$/);
    const h1 = l.match(/^#\s+(.+)$/);
    if (h1 || h2) {
      flushPara(); flushList();
      blocks.push({ type: 'h2', text: (h1 || h2)[1].replace(/^[🌅⚡📋⚖️🧠📰🎯]\s*/, '') });
      continue;
    }
    const bullet = l.match(/^[ \t]*[-*]\s+(.+)$/);
    if (bullet) { flushPara(); listBuf.push(bullet[1]); continue; }
    flushList();
    para.push(l);
  }
  flushPara(); flushList();
  return blocks;
}

function adaptBriefForHero(prodBrief) {
  if (!prodBrief) return null;
  const top3 = extractTop3FromMarkdown(prodBrief.content || '');
  const blocks = markdownToBlocks(prodBrief.content || '');
  return {
    ...prodBrief,
    short_summary: prodBrief.short_summary || (top3[0]?.title ? `${top3[0].title}` : ''),
    tools_used: Array.isArray(prodBrief.tools_used) ? prodBrief.tools_used : [],
    consult_targets: Array.isArray(prodBrief.consult_targets) ? prodBrief.consult_targets : [],
    content: blocks,
    top3: top3.length > 0 ? top3 : [{ title: prodBrief.short_summary || 'Brief hazır', detail: '', action: '', light: 'amber' }],
  };
}

// --- Daily Brief Hero Card ---
const BriefHero = ({ brief, onOpenFull, onRefresh, onDismiss, refreshing }) => {
  const [collapsed, setCollapsed] = React.useState(false);
  const minutesAgo = brief ? Math.max(1, Math.round((Date.now() - new Date(brief.generated_at).getTime()) / 60000)) : 0;

  if (!brief) {
    return (
      <section className="brief-hero brief-hero-empty">
        <div className="brief-empty-glyph"><Icon name="sparkle" size={22} /></div>
        <div className="brief-empty-title">Chief of Staff bugünün brief'ini hazırlıyor</div>
        <div className="brief-empty-sub">İlk brief 30–90 saniye sürer. Cron her sabah 06:00'da otomatik üretir; şimdi de tetikleyebilirsin.</div>
        <button className="brief-empty-cta" onClick={onRefresh} disabled={refreshing}>
          <Icon name="sparkle" size={13} className="sparkle" />
          {refreshing ? "Brief üretiliyor…" : "Brief'i şimdi üret"}
        </button>
      </section>
    );
  }

  return (
    <section className={`brief-hero ${collapsed ? 'collapsed' : ''} ${refreshing ? 'refreshing' : ''}`}>
      <div className="brief-hero-rail" />
      {refreshing && <div className="brief-hero-progress"><span /></div>}

      <header className="brief-hero-head">
        <div className="brief-hero-pill">
          <span className="agent-pill"><Icon name="sparkle" size={11} className="sparkle" />Chief of Staff</span>
          <span className="brief-hero-tag">Daily Brief</span>
        </div>
        <div className="brief-hero-meta">
          <span className="bh-meta-cell"><Icon name="cloud-sun" size={12} /> {todayTR().split(' · ')[0]}</span>
          <span className="bh-meta-dot" />
          <span className="bh-meta-cell">{minutesAgo} dk önce</span>
          <span className="bh-meta-dot" />
          <span className="bh-meta-cell" title={brief.tools_used.join(', ')}>
            <Icon name="tool" size={11} /> {brief.tools_used.length} araç
          </span>
          <button
            className="brief-hero-collapse"
            onClick={() => setCollapsed(c => !c)}
            title={collapsed ? "Brief'i aç" : "Brief'i daralt"}
          >
            <Icon name="chevron-d" size={14} />
          </button>
        </div>
      </header>

      {collapsed ? (
        <div className="brief-hero-summary" onClick={() => setCollapsed(false)}>
          <span className="brief-hero-summary-glyph">{STOPLIGHT[brief.top3[0].light] || '🟡'}</span>
          <span className="brief-hero-summary-text">{brief.short_summary}</span>
          <span className="brief-hero-summary-cta">Aç →</span>
        </div>
      ) : (
        <>
          <div className="brief-hero-lede">
            <span className="brief-hero-lede-flag">⚡</span>
            <span>Bugün öne çıkan</span>
          </div>

          <ol className="brief-top3">
            {brief.top3.map((item, i) => (
              <li key={i} className="brief-top3-item" style={{ animationDelay: `${80 + i * 80}ms` }}>
                <div className="brief-top3-num">{i + 1}</div>
                <div className="brief-top3-body">
                  <div className="brief-top3-title">
                    <span className="brief-top3-light">{STOPLIGHT[item.light]}</span>
                    {item.title}
                  </div>
                  <div className="brief-top3-detail">{item.detail}</div>
                  <div className="brief-top3-action">
                    <Icon name="flag" size={11} />
                    <span>{item.action}</span>
                  </div>
                </div>
              </li>
            ))}
          </ol>

          <footer className="brief-hero-actions">
            <button className="bh-btn bh-btn-primary" onClick={onOpenFull}>
              <Icon name="maximize" size={12} /> Tümünü aç
            </button>
            <button className="bh-btn" onClick={onRefresh} disabled={refreshing}>
              <Icon name="refresh-cw" size={12} className={refreshing ? 'spin' : ''} />
              {refreshing ? 'Yeniden hazırlıyor…' : 'Yeniden oluştur'}
            </button>
            <button className="bh-btn bh-btn-ghost" onClick={onDismiss}>
              <Icon name="eye-off" size={12} /> Bugün gizle
            </button>
          </footer>
        </>
      )}
    </section>
  );
};

// --- Brief full modal (Tümünü aç) ---
const BriefModal = ({ brief, onClose }) => {
  if (!brief) return null;
  return (
    <div className="brief-modal-overlay" onClick={onClose}>
      <div className="brief-modal" onClick={e => e.stopPropagation()}>
        <header className="brief-modal-head">
          <div className="brief-modal-title">
            <span className="agent-pill"><Icon name="sparkle" size={11} className="sparkle" />Chief of Staff</span>
            <h2>Daily Brief — {new Date(brief.brief_date).toLocaleDateString('tr-TR', { day: 'numeric', month: 'long', year: 'numeric' })}</h2>
          </div>
          <button className="brief-modal-x" onClick={onClose}><Icon name="x" size={16} /></button>
        </header>
        <div className="brief-modal-body">
          {brief.content.map((b, i) => {
            if (b.type === 'h2') return <h3 key={i} className="bm-h2">{b.text}</h3>;
            if (b.type === 'p')  return <p  key={i} className="bm-p">{b.text}</p>;
            if (b.type === 'ul') return (
              <ul key={i} className="bm-ul">
                {b.items.map((it, j) => <li key={j}>{it}</li>)}
              </ul>
            );
            if (b.type === 'firstaction') return (
              <div key={i} className="bm-firstaction">{b.text}</div>
            );
            if (b.type === 'top3') return (
              <ol key={i} className="bm-top3">
                {brief.top3.map((it, j) => (
                  <li key={j}>
                    <span className="bm-top3-num">{j + 1}</span>
                    <span className="bm-top3-light">{STOPLIGHT[it.light]}</span>
                    <div className="bm-top3-text">
                      <strong>{it.title}</strong>
                      <span>{it.detail}</span>
                    </div>
                  </li>
                ))}
              </ol>
            );
            return null;
          })}

          <div className="brief-modal-meta">
            <span><Icon name="tool" size={11} /> Kullanılan araçlar</span>
            <div className="bm-toolchips">
              {brief.tools_used.map((t, i) => <span key={i} className="bm-toolchip">{t}</span>)}
            </div>
            {brief.consult_targets?.length > 0 && (
              <>
                <span><Icon name="group" size={11} /> Danışılan ajanlar</span>
                <div className="bm-toolchips">
                  {brief.consult_targets.map((id) => {
                    const a = AGENTS.find(x => x.id === id);
                    return <span key={id} className="bm-toolchip bm-toolchip-agent">{a ? a.name : id}</span>;
                  })}
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

// --- Compact ask bar (under brief) ---
const AskBar = ({ onSendChat }) => {
  const [msg, setMsg] = React.useState('');
  const [focused, setFocused] = React.useState(false);
  const taRef = React.useRef(null);
  const send = () => { if (!msg.trim()) return; onSendChat(msg.trim()); setMsg(''); };

  return (
    <section className={`ask-bar ${focused ? 'focused' : ''}`}>
      <div className="ask-bar-row">
        <span className="ask-bar-label"><Icon name="sparkle" size={11} className="sparkle" />Sor</span>
        <textarea
          ref={taRef}
          className="ask-bar-textarea"
          placeholder="Chief of Staff'a sor — örn. 'Bu çeyreğin EBITDA'sı ne?'"
          value={msg}
          onChange={(e) => {
            setMsg(e.target.value);
            e.target.style.height = 'auto';
            e.target.style.height = Math.min(e.target.scrollHeight, 140) + 'px';
          }}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
          rows={1}
        />
        <button className="ask-bar-mic" title="Sesli giriş"><Icon name="mic" size={14} /></button>
        <button className={`ask-bar-send ${msg.trim() ? 'visible' : ''}`} onClick={send} title="Gönder">
          <Icon name="arrow-up" size={14} />
        </button>
      </div>
      <div className="ask-bar-chips">
        {SUGGESTIONS.map((s, i) => (
          <button key={i} className="chip" onClick={() => { setMsg(s); taRef.current?.focus(); }}>{s}</button>
        ))}
      </div>
    </section>
  );
};

// --- Home main ---
const HomeScreen = ({ onSendChat, onOpenMeeting, tasks = [], onToggleTask, hour, news, home, meetings = [], agents = [] }) => {
  // Prod backend → Hero shape adaptation
  const propBrief = home?.cosBrief || null;
  const [brief, setBrief] = React.useState(() => adaptBriefForHero(propBrief));
  const [refreshing, setRefreshing] = React.useState(false);
  const [showFull, setShowFull] = React.useState(false);
  const [dismissed, setDismissed] = React.useState(false);

  // Sync brief with parent prop when backend updates (cron, post-refresh fetch)
  React.useEffect(() => {
    if (!dismissed) setBrief(adaptBriefForHero(propBrief));
  }, [propBrief, dismissed]);

  // Saat dilimine göre body data attr (aurora gradient'i değiştirir)
  React.useEffect(() => {
    document.documentElement.setAttribute('data-daypart', daypartFor(hour));
    return () => document.documentElement.removeAttribute('data-daypart');
  }, [hour]);

  // Backend bağlı brief refresh
  const handleRefresh = async () => {
    if (refreshing) return;
    setRefreshing(true);
    try {
      const res = await fetch('/api/daily-brief/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ trigger_type: 'on_demand' }),
      });
      if (!res.ok) {
        const j = await res.json().catch(() => ({}));
        alert('Brief üretilemedi: ' + (j.error || res.status));
        return;
      }
      const data = await res.json();
      if (data?.brief) {
        setBrief(adaptBriefForHero(data.brief));
        setDismissed(false);
      } else {
        // Trigger parent home reload (app.jsx listens to event)
        window.dispatchEvent(new CustomEvent('home:refresh'));
      }
    } catch (err) {
      alert('Brief üretilemedi: ' + err.message);
    } finally {
      setRefreshing(false);
    }
  };
  const handleDismiss = () => { setDismissed(true); setBrief(null); };

  // News + notes + meetings backend'den geliyor (fallback: mock)
  const turkeyNews = news?.turkey || (typeof NEWS_LOCAL !== 'undefined' ? NEWS_LOCAL : []);
  const globalNews = news?.global || (typeof NEWS_WORLD !== 'undefined' ? NEWS_WORLD : []);
  const teamNotes  = home?.notes  || (typeof NOTES !== 'undefined' ? NOTES : []);
  const recentMeetings = (home?.recentMeetings || meetings || []).slice(0, 5);

  return (
    <div className="fade-in home-v3" data-daypart={daypartFor(hour)}>
      <div className="home-aurora" aria-hidden="true" />

      <section className="hero-greeting">
        <h1>{greetingFor(hour)}</h1>
        <div className="hero-greeting-meta">
          <span>{todayTR()}</span>
          <span className="dot-sep" />
          <span><Icon name="cloud-sun" size={12} /> İzmir 22°C parçalı bulutlu</span>
          <span className="hero-mood">Bugün 2 toplantı, 3 onay bekliyor.</span>
        </div>
      </section>

      <BriefHero
        brief={brief}
        refreshing={refreshing}
        onOpenFull={() => setShowFull(true)}
        onRefresh={handleRefresh}
        onDismiss={handleDismiss}
      />

      <AskBar onSendChat={onSendChat} />

      <div className="section-head">
        <h2>Hub</h2>
        <span className="see-all">Tümünü gör →</span>
      </div>

      <div className="brief-grid">
        <div className="brief-col">
          <div className="brief-col-head">
            <div className="brief-col-title"><span className="ico"><Icon name="globe" size={13}/></span>Dünya</div>
            <span className="brief-col-link">→</span>
          </div>
          {globalNews.length === 0 && (
            <div className="news-item news-item-empty">Henüz haber yok. Backend cron 4 saatte bir günceller.</div>
          )}
          {globalNews.slice(0, 3).map((n, i) => (
            <div key={n.id || i} className="news-item">
              <div className="news-source">
                <span className="src-badge">{n.source || n.src}</span>
                <span className="news-when">{n.relative_time || (n.fetched_at ? '' : '14 dk önce')}</span>
              </div>
              <div className="news-title">{n.title}</div>
              <div className="news-summary">{n.hook || n.summary || n.sum || ''}</div>
            </div>
          ))}
        </div>

        <div className="brief-col">
          <div className="brief-col-head">
            <div className="brief-col-title"><span className="ico"><Icon name="pin" size={13}/></span>İzmir & KW</div>
            <span className="brief-col-link">→</span>
          </div>
          {turkeyNews.length === 0 && (
            <div className="news-item news-item-empty">Türkiye haberleri yükleniyor.</div>
          )}
          {turkeyNews.slice(0, 3).map((n, i) => (
            <div key={n.id || i} className="news-item">
              <div className="news-source">
                <span className="src-badge">{n.source || n.src}</span>
                <span className="news-when">{n.relative_time || ''}</span>
              </div>
              <div className="news-title">{n.title}</div>
              <div className="news-summary">{n.hook || n.summary || n.sum || ''}</div>
              {n.why_relevant && <div className="news-why">→ Sizin için: {n.why_relevant}</div>}
            </div>
          ))}
        </div>

        <div className="brief-col">
          <div className="brief-col-head">
            <div className="brief-col-title"><span className="ico"><Icon name="lightbulb" size={13}/></span>Ekibin notları</div>
            <span className="brief-col-link">→</span>
          </div>
          {teamNotes.length === 0 && (
            <div className="note-item note-item-empty">Henüz not yok. Ekiple sohbet ettikçe burada özet düşer.</div>
          )}
          {teamNotes.map((n, i) => (
            <div key={i} className="note-item">
              <span className="note-emoji">{n.emoji}</span>
              <div className="note-body">
                <div className="note-text">{n.text}</div>
                <div className="note-meta">{n.who} • {n.when}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="section-head">
        <h2>Devam edenler</h2>
      </div>

      <div className="bottom-grid">
        <div className="panel">
          <div className="panel-head">
            <div className="panel-title">Son toplantılar</div>
            <span className="see-all">Tümü</span>
          </div>
          {recentMeetings.length === 0 && (
            <div className="meeting-row" style={{ padding: 16, color: 'var(--text-tertiary)', fontStyle: 'italic' }}>
              Henüz toplantı yok. Ekibinle ilk sohbeti başlat.
            </div>
          )}
          {recentMeetings.map(m => {
            const agentIds = Array.isArray(m.agents) ? m.agents : (typeof m.agents === 'string' ? m.agents.split(',').filter(Boolean) : []);
            const agentList = Array.isArray(agents) && agents.length > 0 ? agents : (window.AGENTS || []);
            const ags = agentIds.map(id => agentList.find(a => a.id === id)).filter(Boolean);
            return (
              <div key={m.id} className="meeting-row" onClick={() => onOpenMeeting(m)}>
                <div className="meeting-ico"><Icon name="group" size={15} /></div>
                <div className="meeting-mid">
                  <div className="meeting-topic">{m.topic}</div>
                  <div className="meeting-sub">
                    <span className="avatar-stack">
                      {ags.map(a => (
                        <span key={a.id} className="avatar-mini" style={{ background: a.color }}>{a.avatar}</span>
                      ))}
                    </span>
                    <span>{m.when}</span>
                  </div>
                </div>
                <span className="meeting-open">Aç</span>
              </div>
            );
          })}
        </div>

        <div className="panel">
          <div className="panel-head">
            <div className="panel-title">Bugün için</div>
            <span className="see-all">{tasks.filter(t => !t.done).length} bekleyen</span>
          </div>
          {tasks.map(t => (
            <div key={t.id} className={`task-row ${t.done ? 'done' : ''}`}>
              <div className={`task-checkbox ${t.done ? 'checked' : ''}`} onClick={() => onToggleTask(t.id)}>
                <Icon name="check" size={11} />
              </div>
              <div className="task-title">{t.title}</div>
              <span className={`task-due ${t.urgent && !t.done ? 'urgent' : ''}`}>{t.due}</span>
            </div>
          ))}
        </div>
      </div>

      {showFull && <BriefModal brief={brief} onClose={() => setShowFull(false)} />}
    </div>
  );
};

window.HomeScreen = HomeScreen;
