// Portal & chat-style mock primitives for digstaff v9.
// Visual idiom: "office in your messenger" — topic-grouped chat threads.
// Generic chat UI (not a pixel-perfect clone of any specific messenger).

function PortalChrome({ children, dense=false, dark=false, className='', style={} }) {
  const C = window.DT.color;
  const bg = dark ? C.panel : '#FFFFFF';
  const border = dark ? '1px solid rgba(247,244,236,0.10)' : '1px solid rgba(19,17,14,0.08)';
  const shadow = dark
    ? '0 30px 80px -24px rgba(0,0,0,0.55), 0 6px 20px rgba(0,0,0,0.20)'
    : '0 30px 80px -24px rgba(19,17,14,0.18), 0 6px 20px rgba(19,17,14,0.06)';
  return (
    <div className={`relative ${className}`} style={{ background:bg, border, boxShadow:shadow, borderRadius:14, overflow:'hidden', ...style }}>
      {children}
    </div>
  );
}

function PortalTopbar({ dark=false, title='AI-офис', subtitle='ООО «Ромашка»' }) {
  const C = window.DT.color;
  const fg  = dark ? 'rgba(247,244,236,0.92)' : C.ink;
  const fg2 = dark ? 'rgba(247,244,236,0.50)' : C.inkMute;
  const line= dark ? 'rgba(247,244,236,0.10)' : 'rgba(19,17,14,0.08)';
  return (
    <div className="flex items-center justify-between px-5 py-3" style={{ borderBottom:`1px solid ${line}` }}>
      <div className="flex items-center gap-3 min-w-0">
        <span className="w-9 h-9 rounded-xl flex items-center justify-center text-[16px] flex-shrink-0"
          style={{ background:`${C.grass}1F`, border:`1px solid ${C.grass}38` }}>
          🏢
        </span>
        <div className="min-w-0">
          <div className="flex items-center gap-2">
            <span className="text-[13px] font-bold tracking-[-0.01em] truncate" style={{ color:fg, fontFamily:window.DT.font.display }}>
              {title}
            </span>
            <span className="text-[9px] uppercase tracking-[0.14em] px-1.5 py-0.5 rounded-full"
              style={{ color:C.grass, background:dark?'rgba(92,138,58,0.16)':'rgba(92,138,58,0.10)', fontFamily:window.DT.font.mono, fontWeight:700 }}>
              ● live
            </span>
          </div>
          <div className="text-[11px] tabular-nums" style={{ color:fg2, fontFamily:window.DT.font.mono }}>
            {subtitle} · 12 топиков · вся команда онлайн
          </div>
        </div>
      </div>
      <div className="flex items-center gap-2 flex-shrink-0">
        <span className="w-2 h-2 rounded-full animate-pulse" style={{ background:C.grass, boxShadow:`0 0 8px ${C.grass}AA` }}/>
      </div>
    </div>
  );
}

function PortalKPIs({ dark=false }) {
  const C = window.DT.color;
  const fg  = dark ? '#F7F4EC' : C.ink;
  const fg2 = dark ? 'rgba(247,244,236,0.55)' : C.inkMute;
  const line= dark ? 'rgba(247,244,236,0.10)' : 'rgba(19,17,14,0.08)';
  const items = [
    { v:'47',   l:'выполнено',          c:fg },
    { v:'12',   l:'в работе',           c:fg },
    { v:'2',    l:'ждут подтверждения', c:C.accent },
    { v:'10/10',l:'сотрудников онлайн', c:C.grass },
  ];
  return (
    <div className="grid grid-cols-4 px-5 py-4" style={{ borderBottom:`1px solid ${line}` }}>
      {items.map((s,i)=>(
        <div key={i} className={i?'pl-4':''} style={i?{ borderLeft:`1px solid ${line}` }:{}}>
          <div className="text-[22px] font-medium tabular-nums tracking-[-0.025em] leading-none"
            style={{ color:s.c, fontFamily:window.DT.font.display }}>{s.v}</div>
          <div className="mt-1.5 text-[10px] uppercase tracking-[0.10em]"
            style={{ color:fg2, fontFamily:window.DT.font.mono }}>{s.l}</div>
        </div>
      ))}
    </div>
  );
}

function FeedRow({ ev, dark=false, fresh=false, compact=false }) {
  const C = window.DT.color;
  const role = window.EMPLOYEES.find(e=>e.id===ev.role) || { short:ev.role, dot:C.inkMute, emoji:'•' };
  const fg  = dark ? '#F7F4EC' : C.ink;
  const fg2 = dark ? 'rgba(247,244,236,0.55)' : C.inkMute;
  const line= dark ? 'rgba(247,244,236,0.08)' : 'rgba(19,17,14,0.06)';
  const stateColor =
    ev.kind==='approval'    ? C.accent :
    ev.kind==='attention'   ? C.warn :
    ev.kind==='in_progress' ? '#3970C2' :
    C.grass;
  return (
    <div className={`grid items-start gap-3 ${compact?'py-2':'py-2.5'}`}
      style={{ gridTemplateColumns:'48px 1fr auto', borderBottom:`1px solid ${line}` }}>
      <span className="text-[11px] tabular-nums pt-px" style={{ color:fg2, fontFamily:window.DT.font.mono }}>{ev.t}</span>
      <div>
        <div className="flex items-center gap-2 mb-0.5">
          <span className="text-[12px] leading-none">{role.emoji}</span>
          <span className="text-[10px] uppercase tracking-[0.10em] font-bold" style={{ color:fg2, fontFamily:window.DT.font.mono }}>
            {role.short}
          </span>
        </div>
        <div className="text-[12.5px] leading-[1.4]" style={{ color:fg }}>{ev.text}</div>
      </div>
      <div className="flex items-center gap-2 pt-1">
        {ev.kind==='approval' && <StatusPill kind="approval" />}
        <span className="w-1.5 h-1.5 rounded-full mt-px"
          style={{ background:stateColor, boxShadow:fresh?`0 0 0 4px ${stateColor}33`:'none' }} />
      </div>
    </div>
  );
}

// Compact portal — used in hero right column.
// Layout: chat-app header → 3 curated message rows → approval strip. (No KPI bar — was visual noise.)
function PortalCompact() {
  const C = window.DT.color;
  // Curated 3 messages — most informative snapshot of current office state.
  const curated = [
    { t:'10:14', role:'sales',     text:'Сделка ООО «Восход» · 480 000 ₽ — ждёт вашего «ок»', kind:'approval' },
    { t:'10:14', role:'lawyer',    text:'Договор № 2026-118 — 3 правки готовы',                kind:'done' },
    { t:'09:41', role:'director',  text:'Сводка дня для CEO к 17:00 — собираю',              kind:'in_progress' },
  ];
  return (
    <PortalChrome>
      <PortalTopbar/>
      <div className="px-5 py-2">
        {curated.map((ev,i)=>(<FeedRow key={i} ev={ev} fresh={i===0} />))}
      </div>
      <div className="px-5 py-3.5 flex items-center justify-between"
        style={{ background:'rgba(194,84,48,0.06)', borderTop:'1px solid rgba(194,84,48,0.18)' }}>
        <div className="flex items-center gap-2.5">
          <span className="w-2 h-2 rounded-full animate-pulse" style={{ background:C.accent }}/>
          <span className="text-[12px] font-semibold" style={{ color:C.ink }}>
            Нужно подтверждение
          </span>
        </div>
        <span className="text-[11px] uppercase tracking-[0.12em] font-bold flex items-center gap-1"
          style={{ color:C.accent, fontFamily:window.DT.font.mono }}>
          /tasks <Icon name="ArrowRight" size={11} stroke={2.4}/>
        </span>
      </div>
    </PortalChrome>
  );
}

// Chat-bubble primitive — generic messenger style. Used in DemoScenario + Hero teaser.
function ChatMessage({ emoji, name, color, time, children, system=false, ownDir=false, mono=false }) {
  const C = window.DT.color;
  if (system) {
    return (
      <div className="my-2 flex justify-center">
        <div className="px-3 py-1.5 rounded-full text-[11px] flex items-center gap-2"
          style={{ background:'rgba(19,17,14,0.04)', color:C.inkMute, fontFamily:window.DT.font.mono, border:'1px dashed rgba(19,17,14,0.15)' }}>
          {emoji && <span>{emoji}</span>}
          <span>{children}</span>
          {time && <span className="opacity-60">· {time}</span>}
        </div>
      </div>
    );
  }
  return (
    <div className={`flex gap-3 mb-3 ${ownDir?'flex-row-reverse':''}`}>
      <span className="w-8 h-8 rounded-xl flex items-center justify-center text-[16px] flex-shrink-0"
        style={{ background: ownDir ? 'rgba(19,17,14,0.06)' : `${color}14`, border: ownDir ? '1px solid rgba(19,17,14,0.08)' : `1px solid ${color}28` }}>
        {emoji}
      </span>
      <div className={`min-w-0 max-w-[88%] ${ownDir?'items-end':'items-start'} flex flex-col`}>
        <div className="flex items-baseline gap-2 mb-1">
          <span className="text-[12px] font-bold" style={{ color: ownDir ? C.ink : color, fontFamily:window.DT.font.display }}>
            {name}
          </span>
          {time && <span className="text-[10px] tabular-nums" style={{ color:C.inkMute, fontFamily:window.DT.font.mono }}>{time}</span>}
        </div>
        <div className="px-3.5 py-2.5 rounded-[14px]"
          style={{
            background: ownDir ? 'rgba(19,17,14,0.04)' : '#FFFFFF',
            border: ownDir ? '1px solid rgba(19,17,14,0.06)' : `1px solid ${color}1F`,
            boxShadow: ownDir ? 'none' : `0 6px 16px -10px ${color}33`,
            borderRadius: ownDir ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
          }}>
          <div className={`text-[13.5px] leading-[1.55] ${mono?'tabular-nums':''}`}
            style={{ color:C.ink, fontFamily: mono ? window.DT.font.mono : window.DT.font.body, whiteSpace:'pre-wrap' }}>
            {children}
          </div>
        </div>
      </div>
    </div>
  );
}

// Office topics list — used in ActivityFeed and Hero.
function TopicsList({ dark=false, compact=false }) {
  const C = window.DT.color;
  const fg  = dark ? 'rgba(247,244,236,0.92)' : C.ink;
  const fg2 = dark ? 'rgba(247,244,236,0.55)' : C.inkMute;
  const line= dark ? 'rgba(247,244,236,0.06)' : 'rgba(19,17,14,0.05)';
  const baseRow = compact ? 'py-1.5' : 'py-2.5';
  const topics = [
    { emoji:'🎯', name:'Общий чат',  badge:'2', badgeKind:'unread' },
    { emoji:'📋', name:'Задачник',   badge:'1', badgeKind:'approval' },
    ...window.EMPLOYEES.map((e,i)=>({
      emoji:e.emoji, name:e.short,
      badge: i===0 ? '3' : i===2 ? '2' : i===3 ? '1' : null,
      badgeKind: i===2 ? 'approval' : 'unread',
    })),
  ];
  return (
    <div>
      {topics.map((t,i)=>(
        <div key={i} className={`flex items-center gap-3 ${baseRow} px-1`}
          style={{ borderBottom: i<topics.length-1 ? `1px solid ${line}` : 'none' }}>
          <span className={`${compact?'w-7 h-7':'w-8 h-8'} rounded-lg flex items-center justify-center text-[15px] flex-shrink-0`}
            style={{ background: dark ? 'rgba(247,244,236,0.05)' : 'rgba(19,17,14,0.04)' }}>
            {t.emoji}
          </span>
          <span className={`${compact?'text-[12.5px]':'text-[13px]'} flex-1 truncate font-medium`} style={{ color:fg }}>{t.name}</span>
          {t.badge && (
            <span className="text-[10px] px-1.5 py-0.5 rounded-full font-bold tabular-nums min-w-[18px] text-center"
              style={{
                background: t.badgeKind==='approval' ? C.accent : (dark?'rgba(247,244,236,0.12)':'rgba(19,17,14,0.10)'),
                color: t.badgeKind==='approval' ? '#FFFFFF' : fg2,
                fontFamily:window.DT.font.mono,
              }}>
              {t.badge}
            </span>
          )}
        </div>
      ))}
    </div>
  );
}

// Hero chat teaser — replaces grass-feet video. Shows a real moment of work.
// Header "AI-офис · ООО «Ромашка»" + a single conversation excerpt.
function HeroChatTeaser() {
  const C = window.DT.color;
  return (
    <div className="relative overflow-hidden"
      style={{
        background:`linear-gradient(180deg, ${C.creamHi} 0%, ${C.surface} 100%)`,
        border:`1px solid ${C.line}`,
        borderRadius:14,
        boxShadow:'0 24px 60px -24px rgba(19,17,14,0.18), 0 6px 16px rgba(19,17,14,0.04)',
      }}>
      {/* header bar */}
      <div className="flex items-center justify-between px-5 py-3" style={{ borderBottom:`1px solid ${C.line}`, background:`${C.creamHi}` }}>
        <div className="flex items-center gap-3">
          <span className="w-8 h-8 rounded-lg flex items-center justify-center text-[15px]"
            style={{ background:`${C.grass}1F`, border:`1px solid ${C.grass}38` }}>🎯</span>
          <div>
            <div className="text-[12.5px] font-bold leading-tight" style={{ color:C.ink, fontFamily:window.DT.font.display }}>
              Общий чат
            </div>
            <div className="text-[10px] tabular-nums" style={{ color:C.inkMute, fontFamily:window.DT.font.mono }}>
              AI-офис · ООО «Ромашка»
            </div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <span className="w-1.5 h-1.5 rounded-full animate-pulse" style={{ background:C.grass }}/>
          <span className="text-[10px] uppercase tracking-[0.14em]" style={{ color:C.grassDeep, fontFamily:window.DT.font.mono, fontWeight:700 }}>
            10 онлайн
          </span>
        </div>
      </div>

      {/* thread */}
      <div className="px-5 pt-4 pb-3">
        <ChatMessage emoji="🧑" name="Вы" color={C.ink} time="10:14" ownDir>
          Иван прислал договор от ООО «Восход». Проверь и посчитай НДС с 1 800 000.
        </ChatMessage>
        <ChatMessage emoji="⚖️" name="Юрист" color="#8A3A3A" time="10:14">
          Договор № 2026-118. Нашёл 3 момента: п.5.2 — пеня 0.5%/день, п.7 — нет акта приёма, п.11 — чужая подсудность.
        </ChatMessage>
        <ChatMessage emoji="🧮" name="Бухгалтер" color="#3F6A4F" time="10:14" mono>
{`НДС 20% из 1 800 000 ₽:
   НДС:        300 000 ₽
   Без НДС:  1 500 000 ₽`}
        </ChatMessage>
      </div>

      {/* status strip */}
      <div className="px-5 py-3 flex items-center justify-between"
        style={{ background:'rgba(194,84,48,0.06)', borderTop:'1px solid rgba(194,84,48,0.18)' }}>
        <span className="text-[11.5px]" style={{ color:C.inkSoft }}>
          📋 <span style={{ fontFamily:window.DT.font.mono, fontWeight:700, color:C.accent }}>1 задача</span> ждёт вашего «ок» в /tasks
        </span>
        <span className="text-[10px] uppercase tracking-[0.12em] font-bold flex items-center gap-1"
          style={{ color:C.accent, fontFamily:window.DT.font.mono }}>
          Открыть <Icon name="ArrowRight" size={10} stroke={2.4}/>
        </span>
      </div>
    </div>
  );
}

Object.assign(window, { PortalChrome, PortalTopbar, PortalKPIs, FeedRow, PortalCompact, ChatMessage, TopicsList, HeroChatTeaser });
