/* Home dashboard — real API data */

const GREETINGS = {
  morning:   ['Доброе утро, Шеф.',  'Good morning, Chef.',   'Guten Morgen, Chef.', 'Bonjour, Chef.'],
  afternoon: ['Добрый день, Шеф.',  'Good afternoon, Chef.', 'Servus, Chef.',       'Bonjour, Chef.'],
  evening:   ['Добрый вечер, Шеф.', 'Good evening, Chef.',   'Guten Abend, Chef.',  'Bonsoir, Chef.'],
  night:     ['Доброй ночи, Шеф.',  'Good night, Chef.',     'Gute Nacht, Chef.',   'Bonne nuit, Chef.'],
};

function timeOfDay(h) {
  if (h >= 6  && h < 12) return 'morning';
  if (h >= 12 && h < 17) return 'afternoon';
  if (h >= 17 && h < 23) return 'evening';
  return 'night';
}

function GreetingPreloader({ phase, tod }) {
  const reelRef = React.useRef(null);
  const contentRef = React.useRef(null);

  // Reel: scroll through the 4 phrases, ending on RU.
  React.useEffect(() => {
    const reel = reelRef.current;
    if (!reel) return;
    reel.style.transition = 'none';
    reel.style.transform = 'translateY(-90px)'; // 3 lines × 30px → last phrase visible
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        reel.style.transition = 'transform 3.6s cubic-bezier(0.16, 1, 0.3, 1)';
        reel.style.transform = 'translateY(0)';
      });
    });
  }, []);

  // FLIP: when settling, translate the reel container to the live greeting position.
  React.useEffect(() => {
    if (phase !== 'settle') return;
    const c = contentRef.current;
    const target = document.querySelector('.hero-greeting .hg-title .greet');
    if (!c || !target) return;
    const cRect = c.getBoundingClientRect();
    const tRect = target.getBoundingClientRect();
    const dx = tRect.left - cRect.left;
    const dy = tRect.top  - cRect.top;
    requestAnimationFrame(() => {
      c.style.transition = 'transform 0.6s cubic-bezier(0.4, 0, 0.2, 1)';
      c.style.transform = `translate(${dx}px, ${dy}px)`;
    });
  }, [phase]);

  const phrases = GREETINGS[tod];

  return (
    <div className={`greet-preloader ${phase}`}>
      <div ref={contentRef} className="gp-content">
        <div className="gp-window">
          <div ref={reelRef} className="gp-reel">
            {phrases.map((p, i) => (
              <div key={i} className="gp-phrase">{p}</div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function HomeMode({ setMode, setInboxState, setChatState }) {
  const statusQ = useApi(() => API.status(), []);
  const inboxQ  = useApi(() => API.inbox(),  []);

  const [now, setNow] = React.useState(() => new Date());
  const [preloadPhase, setPreloadPhase] = React.useState(() => {
    try {
      return sessionStorage.getItem('home_preload_done') ? 'gone' : 'reel';
    } catch (e) {
      return 'reel';
    }
  });
  const greetRef = React.useRef(null); // FLIP target

  React.useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(t);
  }, []);

  // Preloader phase machine: reel (4s) → settle → gone.
  React.useEffect(() => {
    if (preloadPhase === 'reel') {
      const t = setTimeout(() => setPreloadPhase('settle'), 4000);
      return () => clearTimeout(t);
    }
    if (preloadPhase === 'settle') {
      const t = setTimeout(() => {
        try { sessionStorage.setItem('home_preload_done', '1'); } catch (e) {}
        setPreloadPhase('gone');
      }, 650);
      return () => clearTimeout(t);
    }
  }, [preloadPhase]);

  const hh  = String(now.getHours()).padStart(2, '0');
  const mm  = String(now.getMinutes()).padStart(2, '0');
  const tod = timeOfDay(now.getHours());
  const greeting = GREETINGS[tod][0]; // RU only — no rotation in normal mode.

  const projects    = statusQ.data?.projects || [];
  const health      = statusQ.data?.health   || {};
  const ultimate    = statusQ.data?.ultimate_priority;
  const inboxItems  = inboxQ.data?.items  || [];
  const inboxCount  = inboxQ.data?.count  || 0;

  const activeProjects = projects.filter(p => p.status === 'active' && !p.archived);
  const pausedCount    = projects.filter(p => p.status === 'paused').length;

  // Highest-priority active project = focus
  const focusProj = activeProjects.slice().sort((a, b) => b.priority - a.priority)[0] || null;

  // Fetch focus project detail (arcs)
  const focusQ   = useApi(() => focusProj ? API.project(focusProj.name) : Promise.resolve(null), [focusProj?.name]);
  const focusArcs = focusQ.data?.arcs || [];
  const activeArc = focusArcs.find(a => a.status === 'active' || a.status === 'awaiting_user');
  const doneArcs  = focusArcs.filter(a => a.status === 'done').length;
  const totalArcs = focusArcs.length;
  const arcPct    = totalArcs > 0 ? Math.round(doneArcs / totalArcs * 100) : 0;

  const dotSt = (ok) => ok ? 'var(--ag-ok)' : 'var(--ag-fail)';
  const allOk = health.M1 && health.router && health.embedder;
  const anyOk = health.M1 || health.router || health.embedder;
  const healthLabel = allOk ? 'all systems nominal' : anyOk ? '1+ service down' : 'all services down';

  // Dot color hint for inbox items by type
  const dotHint = (type) => {
    if (type?.includes('consilium')) return 'var(--ag-info)';
    if (type?.includes('todo'))      return 'var(--ag-warn)';
    if (type?.includes('linter'))    return 'var(--ag-fail)';
    return 'var(--ag-warn)';
  };

  const goInboxItem = (id) => {
    setInboxState({ view: 'detail', id });
    setMode('inbox');
  };

  const loading = statusQ.loading && inboxQ.loading;

  return (
    <div className="view-fade" style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {preloadPhase !== 'gone' && <GreetingPreloader phase={preloadPhase} tod={tod} />}
      <Header title="Kinley" sub="AI" />

      <div className="app-body" style={{ flex: 1 }}>

        {/* Ultimate banner */}
        {ultimate && (
          <div style={{ padding: '12px 16px 0' }}>
            <div className="ult-banner">
              <div className="ult-row">
                <span className="ult-pill">ULTIMATE PRIORITY</span>
              </div>
              <div className="ult-msg">
                {ultimate.type === 'arc'
                  ? `Фокус: ${ultimate.project} / ${ultimate.name}`
                  : `Фокус: ${ultimate.name}`}
              </div>
            </div>
          </div>
        )}

        {/* Greeting */}
        <div className="hero-greeting">
          <div className="hg-time">{hh}:{mm} · TODAY</div>
          <div className="hg-title">
            <span
              ref={greetRef}
              className="greet"
              style={preloadPhase !== 'gone' ? { visibility: 'hidden' } : undefined}>
              {greeting}
            </span>
          </div>
          <div className="hg-sub">
            {loading
              ? 'Загрузка...'
              : inboxCount > 0
                ? `${inboxCount} ${inboxCount === 1 ? 'уведомление ждёт' : 'уведомлений ждут'} ответа. ${allOk ? 'Backend в норме.' : 'Есть проблемы с сервисами.'}`
                : `Inbox пуст. ${allOk ? 'Backend в норме.' : 'Есть проблемы с сервисами.'}`}
          </div>
        </div>

        {/* Stat row */}
        <div className="home-row-summary">
          <div className="stat">
            <div className="s-num">{inboxCount}</div>
            <div className="s-lbl">Inbox</div>
            <div className="s-trend">{inboxCount > 0 ? 'pending' : 'пусто'}</div>
          </div>
          <div className="stat">
            <div className="s-num">{activeProjects.length}</div>
            <div className="s-lbl">Active proj</div>
            <div className="s-trend">{pausedCount > 0 ? `${pausedCount} paused` : 'all active'}</div>
          </div>
          <div className="stat">
            {focusProj && activeArc
              ? <>
                  <div className="s-num">{arcPct}<span style={{fontSize:13,opacity:0.6}}>%</span></div>
                  <div className="s-lbl">{focusProj.name.slice(0, 10)}</div>
                  <div className="s-trend">{doneArcs}/{totalArcs} arcs</div>
                </>
              : <>
                  <div className="s-num">—</div>
                  <div className="s-lbl">No focus</div>
                  <div className="s-trend">нет проектов</div>
                </>}
          </div>
        </div>

        {/* Current focus card */}
        {focusProj && (
          <div style={{ marginTop: 18 }}>
            <div className="section-link">
              <div className="section-header" style={{ padding: 0, height: 'auto', minHeight: 0 }}>Сейчас в работе</div>
              <span className="sl-action" onClick={() => setMode('status')}>все проекты →</span>
            </div>
            {focusQ.loading
              ? <div style={{ padding: '20px 16px' }}><LoadingSpinner /></div>
              : <div className="focus-card"
                  onClick={() => { setChatState({ view: 'chat', projectId: focusProj.name }); setMode('chat'); }}
                  style={{ cursor: 'pointer' }}>
                  <div className="fc-label">FOCUS · {focusProj.name}</div>
                  {activeArc
                    ? <>
                        <div className="fc-name">
                          {activeArc.title}
                          <span className="chip chip-sm" style={{ background: 'rgba(54,209,220,0.14)', color: 'var(--ag-info)', fontFamily: 'var(--ag-mono)' }}>
                            {activeArc.status}
                          </span>
                        </div>
                        <div className="fc-arc">Arc {doneArcs + 1}/{totalArcs}</div>
                        <div className="fc-bar"><div className="fill" style={{ width: `${arcPct}%` }} /></div>
                        <div className="fc-stats">
                          <span><b>{doneArcs}</b> done · <b>{totalArcs - doneArcs}</b> left</span>
                          <span style={{ marginLeft: 'auto' }}>open chat →</span>
                        </div>
                      </>
                    : <>
                        <div className="fc-name">Нет активных арок</div>
                        <div className="fc-arc">{focusProj.mode} · {focusProj.status}</div>
                        <div className="fc-stats">
                          <span style={{ marginLeft: 'auto' }}>начать чат →</span>
                        </div>
                      </>}
                </div>}
          </div>
        )}

        {!focusProj && !statusQ.loading && (
          <div style={{ marginTop: 18 }}>
            <div className="section-link">
              <div className="section-header" style={{ padding: 0, height: 'auto', minHeight: 0 }}>Проекты</div>
            </div>
            <div style={{ padding: '16px', textAlign: 'center', color: 'var(--tg-theme-hint-color)', fontSize: 14 }}>
              Нет активных проектов. Создайте проект через /newproject в боте.
            </div>
          </div>
        )}

        {/* Quick actions */}
        <div style={{ marginTop: 18 }}>
          <div className="section-link">
            <div className="section-header" style={{ padding: 0, height: 'auto', minHeight: 0 }}>Быстрые действия</div>
          </div>
          <div className="quick-grid">
            <button className="quick-btn" onClick={() => { setChatState({ view: 'select' }); setMode('chat'); }}>
              <div className="qb-ico" style={{ background: 'rgba(54,209,220,0.14)', color: 'var(--ag-info)' }}><Ico name="chat" size={16} /></div>
              <div>
                <div className="qb-lbl">Новый чат</div>
                <div className="qb-sub">to project</div>
              </div>
            </button>
            <button className="quick-btn" onClick={() => setMode('inject')}>
              <div className="qb-ico" style={{ background: 'rgba(255,176,32,0.14)', color: 'var(--ag-warn)' }}><Ico name="inject" size={16} /></div>
              <div>
                <div className="qb-lbl">Inject</div>
                <div className="qb-sub">file / instr</div>
              </div>
            </button>
            <button className="quick-btn" onClick={() => setMode('inbox')}>
              <div className="qb-ico" style={{ background: 'rgba(255,80,80,0.14)', color: 'var(--ag-fail)' }}><Ico name="inbox" size={16} /></div>
              <div>
                <div className="qb-lbl">Inbox</div>
                <div className="qb-sub">{inboxCount > 0 ? `${inboxCount} pending` : 'пусто'}</div>
              </div>
            </button>
            <button className="quick-btn" onClick={() => setMode('status')}>
              <div className="qb-ico" style={{ background: 'rgba(48,209,88,0.14)', color: 'var(--ag-ok)' }}><Ico name="status" size={16} /></div>
              <div>
                <div className="qb-lbl">Status</div>
                <div className="qb-sub">{activeProjects.length} active</div>
              </div>
            </button>
          </div>
        </div>

        {/* Inbox preview */}
        {inboxCount > 0 && (
          <div style={{ marginTop: 18 }}>
            <div className="section-link">
              <div className="section-header" style={{ padding: 0, height: 'auto', minHeight: 0 }}>Свежее в inbox</div>
              <span className="sl-action" onClick={() => setMode('inbox')}>open inbox →</span>
            </div>
            <div className="card-list">
              {inboxItems.slice(0, 3).map(it => (
                <div key={it.id} className="ibx-prev" onClick={() => goInboxItem(it.id)}>
                  <span className="ip-dot" style={{ background: dotHint(it.type) }} />
                  <div className="ip-body">
                    <div className="ip-title">{it.project} · {it.label || it.type}</div>
                    <div className="ip-meta">{it.type}{it.scope_entity_type ? ` · ${it.scope_entity_type}` : ''}</div>
                  </div>
                  <div className="ip-time">{relTime(it.created_at)}</div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Health pulse */}
        <div style={{ marginTop: 18, marginBottom: 8 }}>
          <div className="section-link">
            <div className="section-header" style={{ padding: 0, height: 'auto', minHeight: 0 }}>Сервисы</div>
            <span className="sl-action" onClick={() => setMode('status')}>connections →</span>
          </div>
          <div className="health-pulse">
            <div className="hp-item"><span className="status-dot" style={{ background: dotSt(health.M1) }} /><span className="hp-name">M1</span></div>
            <div className="hp-item"><span className="status-dot" style={{ background: dotSt(health.router) }} /><span className="hp-name">router</span></div>
            <div className="hp-item"><span className="status-dot" style={{ background: dotSt(health.embedder) }} /><span className="hp-name">embedder</span></div>
            <div style={{ marginLeft: 'auto', fontFamily: 'var(--ag-mono)', fontSize: 10.5, color: 'var(--tg-theme-hint-color)' }}>
              {statusQ.loading ? '...' : healthLabel}
            </div>
          </div>
        </div>

        <div style={{ height: 12 }} />
      </div>
    </div>
  );
}

window.HomeMode = HomeMode;
