/* ============================================================
   screen_stories.jsx — Home: weekly pulse + swipeable Stories
   ============================================================ */

/* ---------- mini sparkline (animated draw) ---------- */
function Spark({ color = 'var(--amber)', w = 120, h = 40 }) {
  const pts = [6, 9, 7, 12, 10, 16, 14, 20, 24];
  const max = Math.max(...pts), min = Math.min(...pts);
  const d = pts.map((p, i) => {
    const x = (i / (pts.length - 1)) * w;
    const y = h - ((p - min) / (max - min)) * (h - 6) - 3;
    return `${i === 0 ? 'M' : 'L'}${x.toFixed(1)} ${y.toFixed(1)}`;
  }).join(' ');
  return (
    <svg width={w} height={h} style={{ overflow: 'visible' }}>
      <path d={d} fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
        strokeDasharray="300" strokeDashoffset="300" style={{ animation: 'drawCheck 1.2s var(--ease-out) .2s forwards' }} />
      <circle r="3.5" fill={color}>
        <animateMotion dur="1.2s" begin="0.2s" fill="freeze" path={d} />
      </circle>
    </svg>
  );
}

/* ---------- story card content by type ---------- */
function StoryContent({ s, lang, t, go, onClose }) {
  const valueNum = useCountUp(s.value || s.delta || (s.big ? +s.big : 0), 1100, true);
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', padding: '28px 26px 40px', color: '#fff', position: 'relative', zIndex: 2 }}>
      <div style={{ fontSize: 13, fontWeight: 800, letterSpacing: '.6px', textTransform: 'uppercase', color: s.accent ? 'var(--amber-soft)' : 'rgba(255,255,255,.7)', marginBottom: 16, animation: 'fadeUp .5s .1s both' }}>
        {tr(s.kicker, lang)}
      </div>

      {s.type === 'value' && (
        <div style={{ animation: 'fadeUp .6s .2s both' }}>
          <div style={{ fontSize: 26, fontWeight: 800, lineHeight: 1.15, marginBottom: 18 }}>{tr(s.title, lang)}</div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10 }}>
            <span style={{ fontSize: 46, fontWeight: 800, letterSpacing: '-1.5px', lineHeight: 1 }}>{fmtSum(valueNum)}</span>
            <span style={{ fontSize: 17, fontWeight: 700, color: 'rgba(255,255,255,.6)', marginBottom: 4, whiteSpace: 'nowrap' }}>{t.perMonth}</span>
          </div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 14, padding: '6px 12px', borderRadius: 'var(--r-full)', background: 'rgba(47,191,143,.2)', color: '#7df0c4', fontWeight: 800, fontSize: 14 }}>
            <Icon name="trend" size={16} stroke={2.4} /> +{s.trend}% {t.thisWeek}
          </div>
          <div style={{ marginTop: 22 }}><Spark color="var(--amber)" w={240} h={56} /></div>
        </div>
      )}

      {s.type === 'watchers' && (
        <div style={{ animation: 'fadeUp .6s .2s both' }}>
          <div style={{ fontSize: 92, fontWeight: 800, letterSpacing: '-3px', lineHeight: .9, color: 'var(--amber-soft)' }}>{valueNum}</div>
          <div style={{ fontSize: 24, fontWeight: 800, lineHeight: 1.2, marginTop: 6 }}>{tr(s.title, lang)}</div>
          <div style={{ display: 'flex', marginTop: 18 }}>
            {[0,1,2,3,4].map(i => (
              <span key={i} style={{ width: 34, height: 34, borderRadius: '50%', marginLeft: i ? -10 : 0, background: `linear-gradient(150deg,var(--indigo-400),var(--indigo-600))`, border: '2px solid var(--indigo-900)', display: 'flex', alignItems: 'center', justifyContent: 'center', animation: `popIn .4s ${0.3 + i*0.08}s both` }}>
                <Icon name="eye" size={15} stroke={2} style={{ color: '#fff' }} />
              </span>
            ))}
          </div>
        </div>
      )}

      {s.type === 'demand' && (
        <div style={{ animation: 'fadeUp .6s .2s both' }}>
          <div style={{ fontSize: 28, fontWeight: 800, lineHeight: 1.15 }}>{tr(s.title, lang)}</div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 110, marginTop: 24 }}>
            {[40, 52, 48, 66, 72, 88, 100].map((h, i) => (
              <div key={i} style={{ flex: 1, height: h + '%', borderRadius: 8, transformOrigin: 'bottom',
                background: i >= 5 ? 'linear-gradient(var(--amber-soft),var(--amber))' : 'rgba(255,255,255,.18)',
                animation: `barGrow .6s var(--ease-out) ${0.3 + i*0.07}s both` }} />
            ))}
          </div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 18, fontSize: 17, fontWeight: 800, color: 'var(--amber-soft)' }}>
            <Icon name="trend" size={18} stroke={2.4} /> +{s.delta}%
          </div>
        </div>
      )}

      {s.type === 'role' && (
        <div style={{ animation: 'fadeUp .6s .2s both' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
            <Logo brand={s.brand} size={56} radius={16} />
            <Ring value={s.match} size={56} stroke={6} color="var(--amber)" track="rgba(255,255,255,.15)">
              <span style={{ color: '#fff', fontSize: 14, fontWeight: 800 }}>{s.match}</span>
            </Ring>
          </div>
          <div style={{ fontSize: 34, fontWeight: 800, letterSpacing: '-.8px' }}>{tr(s.title, lang)}</div>
          <div style={{ fontSize: 18, fontWeight: 600, color: 'rgba(255,255,255,.7)', marginTop: 2 }}>{brandName(s.company)}</div>
        </div>
      )}

      {s.type === 'gap' && (
        <div style={{ animation: 'fadeUp .6s .2s both' }}>
          <div style={{ width: 60, height: 60, borderRadius: 18, background: 'rgba(255,107,74,.2)', color: 'var(--hot)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}>
            <Icon name="fire" size={30} stroke={2} />
          </div>
          <div style={{ fontSize: 30, fontWeight: 800, letterSpacing: '-.6px', lineHeight: 1.15 }}>{tr(s.title, lang)}</div>
        </div>
      )}

      {s.type === 'progress' && (
        <div style={{ animation: 'fadeUp .6s .2s both' }}>
          <div style={{ width: 60, height: 60, borderRadius: 18, background: 'rgba(47,191,143,.2)', color: 'var(--good)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}>
            <Icon name="trend" size={30} stroke={2.2} />
          </div>
          <div style={{ fontSize: 32, fontWeight: 800, letterSpacing: '-.6px', lineHeight: 1.15 }}>{tr(s.title, lang)}</div>
          <div style={{ display: 'flex', gap: 6, marginTop: 20 }}>
            {[0,1,2,3,4].map(i => (
              <span key={i} style={{ flex: 1, height: 8, borderRadius: 99, background: i < 3 ? 'var(--good)' : 'rgba(255,255,255,.18)', transformOrigin: 'left', animation: `barGrow .5s var(--ease-out) ${0.3 + i*0.1}s both` }} />
            ))}
          </div>
        </div>
      )}

      <div style={{ fontSize: 16, lineHeight: 1.4, color: 'rgba(255,255,255,.82)', marginTop: 20, fontWeight: 500, animation: 'fadeUp .6s .35s both' }}>
        {tr(s.sub, lang)}
      </div>

      {(s.type === 'role' || s.type === 'watchers' || s.type === 'gap') && (
        <button onClick={() => { onClose(); go(s.type === 'role' ? 'jobs' : s.type === 'gap' ? 'growth' : 'profile'); }} style={{
          marginTop: 24, height: 52, borderRadius: 'var(--r-lg)', background: s.accent ? 'linear-gradient(150deg,var(--amber-soft),var(--amber))' : '#fff',
          color: 'var(--indigo-900)', fontSize: 15.5, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          animation: 'fadeUp .6s .45s both',
        }}>
          {s.type === 'role' ? t.why : s.type === 'gap' ? t.start : t.statusTitle}
          <Icon name="arrow" size={19} stroke={2.4} />
        </button>
      )}
    </div>
  );
}

/* ---------- fullscreen story viewer ---------- */
function StoryViewer({ start, onClose, lang, t, go }) {
  const [i, setI] = useState(start || 0);
  const [paused, setPaused] = useState(false);
  const [prog, setProg] = useState(0);
  const raf = useRef(null);
  const last = useRef(0);
  const DUR = 5200;

  useEffect(() => { setProg(0); last.current = 0; }, [i]);
  useEffect(() => {
    const tick = (ts) => {
      if (!last.current) last.current = ts;
      const dt = ts - last.current; last.current = ts;
      if (!paused) {
        setProg(p => {
          const n = p + dt / DUR;
          if (n >= 1) {
            if (i < STORIES.length - 1) { setI(i + 1); return 0; }
            else { setTimeout(onClose, 0); return 1; }
          }
          return n;
        });
      }
      raf.current = requestAnimationFrame(tick);
    };
    raf.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf.current);
  }, [i, paused]);

  const s = STORIES[i];
  const next = () => { if (i < STORIES.length - 1) setI(i + 1); else onClose(); };
  const prev = () => { if (i > 0) setI(i - 1); else setProg(0); };

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 40, background: 'radial-gradient(120% 90% at 50% 0%, #243066, #0a0f24 75%)', display: 'flex', flexDirection: 'column', animation: 'scaleIn .25s var(--ease-out) both', overflow: 'hidden' }}>
      {/* decorative glow */}
      <div style={{ position: 'absolute', top: -80, right: -60, width: 240, height: 240, borderRadius: '50%', background: s.accent ? 'radial-gradient(circle,var(--amber-glow),transparent 70%)' : 'radial-gradient(circle,rgba(97,115,173,.4),transparent 70%)', filter: 'blur(10px)' }} />

      {/* progress bars */}
      <div style={{ display: 'flex', gap: 5, padding: '10px 14px 0', position: 'relative', zIndex: 3 }}>
        {STORIES.map((_, k) => (
          <div key={k} style={{ flex: 1, height: 3.5, borderRadius: 99, background: 'rgba(255,255,255,.25)', overflow: 'hidden' }}>
            <div style={{ height: '100%', borderRadius: 99, background: '#fff', width: k < i ? '100%' : k === i ? `${prog * 100}%` : '0%' }} />
          </div>
        ))}
      </div>

      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 16px', position: 'relative', zIndex: 3 }}>
        <div style={{ width: 30, height: 30, borderRadius: '50%', background: 'linear-gradient(150deg,var(--amber-soft),var(--amber))', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--indigo-900)' }}><Icon name="spark" size={16} stroke={2.4} /></div>
        <span style={{ color: '#fff', fontWeight: 700, fontSize: 14, flex: 1 }}>{t.weeklyPulse}</span>
        <button onClick={onClose} style={{ color: 'rgba(255,255,255,.8)', width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
        </button>
      </div>

      {/* tap zones */}
      <div style={{ position: 'absolute', inset: 0, zIndex: 2, display: 'flex' }}
        onPointerDown={() => setPaused(true)} onPointerUp={() => setPaused(false)} onPointerLeave={() => setPaused(false)}>
        <div style={{ width: '32%' }} onClick={prev} />
        <div style={{ flex: 1 }} onClick={next} />
      </div>

      <StoryContent key={i} s={s} lang={lang} t={t} go={go} onClose={onClose} />
    </div>
  );
}

/* ---------- story rail bubble ---------- */
function StoryBubble({ s, lang, onOpen, seen }) {
  const label = { value: { ru: 'Неделя', uz: 'Hafta' }, watchers: { ru: 'Тебя ищут', uz: 'Qidirishyapti' }, demand: { ru: 'Спрос', uz: 'Talab' }, role: { ru: 'Роль', uz: 'Rol' }, gap: { ru: 'Шаг', uz: 'Qadam' }, progress: { ru: 'Рост', uz: 'Rivoj' } }[s.type];
  const icon = { value: 'trend', watchers: 'eye', demand: 'spark', role: 'briefcase', gap: 'fire', progress: 'trend' }[s.type];
  return (
    <button onClick={onOpen} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, flexShrink: 0, width: 70 }}>
      <span style={{ width: 64, height: 64, borderRadius: '50%', padding: 2.5, background: seen ? 'var(--border-2)' : 'linear-gradient(150deg,var(--amber),var(--indigo-500))' }}>
        <span style={{ width: '100%', height: '100%', borderRadius: '50%', background: 'var(--surface)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: s.accent ? 'var(--amber-deep)' : 'var(--brand)' }}>
          <Icon name={icon} size={24} stroke={2} />
        </span>
      </span>
      <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-2)', textAlign: 'center', lineHeight: 1.1 }}>{tr(label, lang)}</span>
    </button>
  );
}

/* ---------- home screen ---------- */
function StoriesScreen({ lang, theme, setLang, setTheme, t, go, status }) {
  const [viewer, setViewer] = useState(null); // start index or null
  const [seen, setSeen] = useState([]);
  const hero = STORIES[0];
  const heroVal = useCountUp(hero.value, 1100, true);

  const open = (k) => { setViewer(k); setSeen(p => [...new Set([...p, k])]); };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
      {viewer !== null && <StoryViewer start={viewer} onClose={() => setViewer(null)} lang={lang} t={t} go={go} />}

      <Header
        sub={t.goodMorning + ', ' + tr(PERSONA.name, lang).split(' ')[0]}
        title={t.weeklyPulse}
        right={<QuickToggles lang={lang} setLang={setLang} theme={theme} setTheme={setTheme} />}
        t={t}
      />

      <div className="noscroll" style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '0 16px 20px' }}>
        {/* story rail */}
        <div className="noscroll" style={{ display: 'flex', gap: 12, overflowX: 'auto', padding: '2px 2px 14px' }}>
          {STORIES.map((s, k) => <StoryBubble key={k} s={s} lang={lang} onOpen={() => open(k)} seen={seen.includes(k)} />)}
        </div>

        {/* pulse hero */}
        <button onClick={() => open(0)} style={{
          width: '100%', textAlign: 'left', borderRadius: 'var(--r-xl)', overflow: 'hidden', position: 'relative',
          background: 'radial-gradient(130% 100% at 80% 0%, #2a3a6e, #16203f 70%)', padding: '22px 22px 24px', color: '#fff',
          boxShadow: 'var(--shadow-2)', flexShrink: 0, animation: 'fadeUp .5s var(--ease-out) both',
        }}>
          <div style={{ position: 'absolute', top: -40, right: -30, width: 160, height: 160, borderRadius: '50%', background: 'radial-gradient(circle,var(--amber-glow),transparent 70%)' }} />
          <div style={{ position: 'relative' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, fontWeight: 800, letterSpacing: '.5px', textTransform: 'uppercase', color: 'var(--amber-soft)', marginBottom: 14 }}>
              <Icon name="spark" size={15} stroke={2.4} /> {tr(hero.kicker, lang)}
            </div>
            <div style={{ fontSize: 15, color: 'rgba(255,255,255,.7)', fontWeight: 600, marginBottom: 6 }}>{tr(hero.title, lang)}</div>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14 }}>
              <div>
                <div style={{ display: 'flex', alignItems: 'flex-end', gap: 7 }}>
                  <span style={{ fontSize: 38, fontWeight: 800, letterSpacing: '-1.3px', lineHeight: 1 }}>{fmtSum(heroVal)}</span>
                  <span style={{ fontSize: 13, color: 'rgba(255,255,255,.55)', marginBottom: 4, whiteSpace: 'nowrap' }}>{t.perMonth}</span>
                </div>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 10, padding: '4px 10px', borderRadius: 99, background: 'rgba(47,191,143,.2)', color: '#7df0c4', fontWeight: 800, fontSize: 12.5, whiteSpace: 'nowrap' }}>
                  <Icon name="trend" size={14} stroke={2.4} /> +{hero.trend}% {t.thisWeek}
                </div>
              </div>
              <div style={{ flex: 1, paddingBottom: 4 }}><Spark color="var(--amber)" w={120} h={48} /></div>
            </div>
          </div>
        </button>

        {/* feed cards */}
        <FeedCard onClick={() => open(1)} icon="eye" color="var(--indigo-500)" delay={.08}
          big="14" title={t.seen} sub={tr(STORIES[1].sub, lang)} lang={lang} />
        <FeedCard onClick={() => open(2)} icon="trend" color="var(--good)" delay={.14}
          big="+12%" title={t.demand} sub={tr(STORIES[2].sub, lang)} lang={lang} />
        <FeedCard onClick={() => { setViewer(null); go('jobs'); }} icon="briefcase" color="var(--amber-deep)" delay={.2}
          big="92%" title={tr({ ru: 'Новая роль · SMM-менеджер', uz: 'Yangi rol · SMM menejer' }, lang)} sub={tr(STORIES[3].sub, lang)} lang={lang} />

        {/* who viewed you */}
        <button onClick={() => open(1)} style={{ width: '100%', textAlign: 'left', marginTop: 22, animation: 'fadeUp .5s .24s both', background: 'none' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, padding: '0 2px' }}>
            <span style={{ fontSize: 16, fontWeight: 800, letterSpacing: '-.3px' }}>{t.whoViewed}</span>
            <span style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--text-3)' }}>{t.viewedSub}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', borderRadius: 'var(--r-lg)', background: 'var(--surface)', border: '1px solid var(--border)', boxShadow: 'var(--shadow-1)' }}>
            <div style={{ display: 'flex' }}>
              {VIEWERS.slice(0, 5).map((b, i) => (
                <span key={b} style={{ marginLeft: i ? -12 : 0, borderRadius: 12, border: '2px solid var(--surface)', zIndex: 5 - i }}>
                  <Logo brand={b} size={36} radius={10} />
                </span>
              ))}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14.5, fontWeight: 800 }}>14 {t.employers}</div>
              <div style={{ fontSize: 12, color: 'var(--text-3)' }}>{t.seen}</div>
            </div>
            <Icon name="chevron" size={18} stroke={2.2} style={{ color: 'var(--text-3)' }} />
          </div>
        </button>

        {/* companies hiring rail */}
        <div style={{ marginTop: 22, animation: 'fadeUp .5s .3s both' }}>
          <div style={{ fontSize: 16, fontWeight: 800, letterSpacing: '-.3px', marginBottom: 12, padding: '0 2px' }}>{t.companiesHiring}</div>
          <div className="noscroll" style={{ display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 2 }}>
            {VIEWERS.map(b => (
              <button key={b} onClick={() => go('jobs')} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, flexShrink: 0, width: 70, padding: '14px 6px', borderRadius: 'var(--r-lg)', background: 'var(--surface)', border: '1px solid var(--border)', boxShadow: 'var(--shadow-1)' }}>
                <Logo brand={b} size={42} />
                <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-2)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>{brandName(b)}</span>
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function FeedCard({ icon, color, big, title, sub, onClick, delay = 0 }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', textAlign: 'left', marginTop: 12, padding: '16px', borderRadius: 'var(--r-lg)',
      background: 'var(--surface)', border: '1px solid var(--border)', boxShadow: 'var(--shadow-1)',
      display: 'flex', alignItems: 'center', gap: 14, animation: `fadeUp .5s var(--ease-out) ${delay}s both`,
    }}>
      <span style={{ width: 48, height: 48, borderRadius: 14, flexShrink: 0, background: 'var(--brand-tint)', color, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={icon} size={22} stroke={2.2} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 7 }}>
          <span style={{ fontSize: 19, fontWeight: 800, color: 'var(--text)' }}>{big}</span>
          <span style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--text)' }}>{title}</span>
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--text-3)', marginTop: 3, lineHeight: 1.3 }}>{sub}</div>
      </div>
      <Icon name="chevron" size={18} stroke={2.2} style={{ color: 'var(--text-3)', flexShrink: 0 }} />
    </button>
  );
}

Object.assign(window, { StoriesScreen, StoryViewer });
