/* global React, LIcons */
// Hero: celular com TikTok + dedo fantasma fazendo interações reais em loop.

const { useState: usePhState, useEffect: usePhEffect, useRef: usePhRef } = React;

const PH_VIDEOS = [
  { handle: '@viral.cortes', caption: 'esse corte ficou insano, parte 3', song: 'som original — viral.cortes', hue: 265, likes: 128400, comments: 2310, shares: 890,
    base: [['@ana.clips', 'primeiro!!'], ['@joao.trends', 'caiu no meu fyp kkk']] },
  { handle: '@receitas.da.lu', caption: 'bolo de pote que vende MUITO', song: 'áudio em alta — cozinha lofi', hue: 20, likes: 45200, comments: 1180, shares: 2400,
    base: [['@doce.mania', 'anotei tudo'], ['@confeita.rio', 'quanto rende?']] },
  { handle: '@fit.marcos', caption: 'treino de 12 min sem equipamento', song: 'phonk workout — gym mix', hue: 160, likes: 89100, comments: 940, shares: 1500,
    base: [['@saude.top', 'salvei aqui'], ['@treino.casa', 'fiz hoje, senti demais']] },
  { handle: '@meme.central', caption: 'ele nao esperava por essa', song: 'som original — meme.central', hue: 330, likes: 230500, comments: 8200, shares: 12100,
    base: [['@risada.br', 'CHOREI kkkkk'], ['@zoeira.max', 'marca teu amigo']] },
];

const PH_MSGS = ['salvou demais essa dica!', 'conteudo top, ja segui', 'testei aqui e funcionou', 'melhor video de hoje'];
const PH_WHO = ['@fit.gabi', '@loja.doce.rj', '@moda.achados', '@viral.cortes'];

const PH_POS = {
  hidden: { x: 50, y: 114 },
  center: { x: 50, y: 42 },
  heart: { x: 89, y: 49 },
  comment: { x: 89, y: 58 },
  share: { x: 89, y: 76 },
  input: { x: 42, y: 93 },
  send: { x: 89, y: 93 },
  closeX: { x: 90, y: 41.5 },
  swipeStart: { x: 50, y: 64 },
  swipeEnd: { x: 50, y: 22 },
};

const phFmt = (n) => n >= 1000000 ? (n / 1000000).toFixed(1) + 'M' : n >= 1000 ? (n / 1000).toFixed(n >= 10000 ? 0 : 1) + 'k' : String(n);

function PhoneDemo() {
  const [pos, setPos] = usePhState(PH_POS.hidden);
  const [fast, setFast] = usePhState(false);
  const [vis, setVis] = usePhState(false);
  const [taps, setTaps] = usePhState([]);
  const [vi, setVi] = usePhState(0);
  const [liked, setLiked] = usePhState(false);
  const [likesX, setLikesX] = usePhState(0);
  const [sharesX, setSharesX] = usePhState(0);
  const [burst, setBurst] = usePhState(0);
  const [pop, setPop] = usePhState(null);
  const [sheet, setSheet] = usePhState(false);
  const [typed, setTyped] = usePhState(0);
  const [sent, setSent] = usePhState(false);
  const [myCm, setMyCm] = usePhState(null);
  const [caption, setCaption] = usePhState(['', 'observando o feed...']);
  const typeTimer = usePhRef(null);

  const tapAt = (p) => setTaps(t => [...t.slice(-3), { id: Date.now() + Math.random(), ...p }]);

  usePhEffect(() => {
    let alive = true;
    let timer = null;
    let loop = 0;

    const STEPS = [
      // reset / observar
      { d: 1100, run: () => { setVis(false); setPos(PH_POS.hidden); setSheet(false); setSent(false); setTyped(0); setMyCm(null); setCaption(['', 'observando o feed...']); } },
      { d: 750, run: () => { setVis(true); setFast(false); setPos(PH_POS.center); } },
      // double tap like
      { d: 180, run: () => tapAt(PH_POS.center) },
      { d: 1050, run: (l) => { tapAt(PH_POS.center); setBurst(b => b + 1); setLiked(true); setLikesX(x => x + 1); setPop('like'); setCaption([PH_WHO[l % 4], 'curtiu o vídeo']); } },
      // abrir comentários
      { d: 720, run: () => setPos(PH_POS.comment) },
      { d: 950, run: () => { tapAt(PH_POS.comment); setSheet(true); setCaption([PH_WHO[loop % 4], 'abriu os comentários']); } },
      // digitar
      { d: 650, run: () => setPos(PH_POS.input) },
      { d: 300, run: () => tapAt(PH_POS.input) },
      { d: 1500, run: (l) => {
          setCaption([PH_WHO[l % 4], 'comentando...']);
          const msg = PH_MSGS[l % PH_MSGS.length];
          let k = 0;
          clearInterval(typeTimer.current);
          typeTimer.current = setInterval(() => {
            k++; setTyped(k);
            if (k >= msg.length) clearInterval(typeTimer.current);
          }, 55);
        } },
      // enviar
      { d: 560, run: () => setPos(PH_POS.send) },
      { d: 1000, run: (l) => { tapAt(PH_POS.send); setSent(true); setMyCm([PH_WHO[l % 4], PH_MSGS[l % PH_MSGS.length]]); setTyped(0); setCaption([PH_WHO[l % 4], 'enviou um comentário']); } },
      // fechar sheet
      { d: 580, run: () => setPos(PH_POS.closeX) },
      { d: 800, run: () => { tapAt(PH_POS.closeX); setSheet(false); setSent(false); } },
      // compartilhar
      { d: 700, run: () => setPos(PH_POS.share) },
      { d: 900, run: (l) => { tapAt(PH_POS.share); setSharesX(x => x + 1); setPop('share'); setCaption([PH_WHO[l % 4], 'compartilhou o vídeo']); } },
      // swipe
      { d: 520, run: () => { setFast(false); setPos(PH_POS.swipeStart); } },
      { d: 420, run: () => { setFast(true); setPos(PH_POS.swipeEnd); setCaption(['', 'próximo vídeo...']); } },
      { d: 400, run: () => { setVi(v => v + 1); setLiked(false); setPop(null); } },
    ];

    let i = 0;
    const next = () => {
      if (!alive) return;
      const s = STEPS[i % STEPS.length];
      if (i > 0 && i % STEPS.length === 0) loop++;
      s.run(loop);
      timer = setTimeout(next, s.d);
      i++;
    };
    next();
    return () => { alive = false; clearTimeout(timer); clearInterval(typeTimer.current); };
  }, []);

  const v = PH_VIDEOS[vi % PH_VIDEOS.length];
  const typing = PH_MSGS[vi % PH_MSGS.length].slice(0, typed);
  const cmts = myCm ? [myCm, ...v.base] : v.base;

  return (
    <div className="ph">
      <div className="ph-screen">
        {/* vídeo */}
        <div className="tk-video" key={vi}
          style={{ background: `linear-gradient(165deg, hsl(${v.hue} 45% 24%) 0%, hsl(${(v.hue + 40) % 360} 42% 10%) 58%, #030303 100%)` }}></div>
        <div className="ph-punch"></div>
        <div className="ph-status"><span>20:41</span><span>5G</span></div>
        <div className="tk-top"><span>Seguindo</span><span className="on">Para você</span></div>

        {/* burst do like */}
        {pop === 'like' && burst > 0 && (
          <span className="tk-burst" key={burst}>
            <LIcons.Heart size={92} sw={0} style={{ fill: '#fe2c55', stroke: 'none' }}/>
          </span>
        )}

        {/* rail */}
        <div className="tk-rail">
          <div className="tk-av" style={{ background: `linear-gradient(140deg, hsl(${v.hue} 40% 35%), #111)` }}>
            {v.handle[1].toUpperCase()}<span className="plus">+</span>
          </div>
          <div className="tk-btn">
            <span className={pop === 'like' ? 'tk-pop' : ''} key={'h' + likesX}>
              <LIcons.Heart size={27} sw={0} style={{ fill: liked ? '#fe2c55' : '#fff', stroke: 'none' }}/>
            </span>
            <span className="tk-count">{phFmt(v.likes + likesX)}</span>
          </div>
          <div className="tk-btn">
            <LIcons.Comment size={26} sw={0} style={{ fill: '#fff', stroke: 'none' }}/>
            <span className="tk-count">{phFmt(v.comments + (myCm ? 1 : 0))}</span>
          </div>
          <div className="tk-btn">
            <LIcons.Bookmark size={25} sw={0} style={{ fill: '#fff', stroke: 'none' }}/>
            <span className="tk-count">{phFmt(Math.round(v.likes / 40))}</span>
          </div>
          <div className="tk-btn">
            <span className={pop === 'share' ? 'tk-pop' : ''} key={'s' + sharesX}>
              <LIcons.Share size={26} sw={0} style={{ fill: '#fff', stroke: 'none' }}/>
            </span>
            <span className="tk-count">{phFmt(v.shares + sharesX)}</span>
          </div>
          <div className="tk-disc" style={{ background: `conic-gradient(from 0deg, hsl(${v.hue} 50% 45%), #222, hsl(${v.hue} 50% 45%))` }}></div>
        </div>

        {/* info */}
        <div className="tk-info">
          <span className="tk-handle">{v.handle}</span>
          <span className="tk-caption">{v.caption}</span>
          <span className="tk-music"><LIcons.Music size={11}/><span>{v.song}</span></span>
        </div>

        {/* sheet de comentários */}
        <div className={`tk-sheet ${sheet ? 'open' : ''}`}>
          <div className="tk-sheet-head">
            {phFmt(v.comments + (myCm ? 1 : 0))} comentários
            <span className="tk-sheet-x"><LIcons.Close size={14}/></span>
          </div>
          <div className="tk-comments">
            {cmts.map((c, idx) => (
              <div className={`tk-cm ${myCm && idx === 0 ? 'tk-cm-new' : ''}`} key={c[0] + idx + (myCm ? 'n' : '')}>
                <span className="tk-cm-av" style={{ background: `hsl(${(v.hue + idx * 70) % 360} 35% 30%)` }}>{c[0][1].toUpperCase()}</span>
                <span className="tk-cm-body">
                  <span className="tk-cm-user" style={{ display: 'block' }}>{c[0]}</span>
                  <span className="tk-cm-text">{c[1]}</span>
                </span>
              </div>
            ))}
          </div>
          <div className="tk-input">
            {typed > 0
              ? <span>{typing}<span className="tk-caret"></span></span>
              : <span className="ph-text">Adicione um comentário...</span>}
            <span className={`tk-send ${typed > 0 ? 'ready' : ''} ${sent ? 'sent' : ''}`}><LIcons.Send size={14}/></span>
          </div>
        </div>

        {/* dedo fantasma + rastro */}
        <span className="fg-t fg-t3" style={{ left: pos.x + '%', top: pos.y + '%', opacity: vis ? 0.5 : 0 }}></span>
        <span className="fg-t fg-t2" style={{ left: pos.x + '%', top: pos.y + '%', opacity: vis ? 0.6 : 0 }}></span>
        <span className="fg-t fg-t1" style={{ left: pos.x + '%', top: pos.y + '%', opacity: vis ? 0.7 : 0 }}></span>
        <span className={`fg ${fast ? 'fast' : ''}`} style={{ left: pos.x + '%', top: pos.y + '%', opacity: vis ? 1 : 0 }}></span>
        {taps.map(t => (
          <span className="fg-tap" key={t.id} style={{ left: t.x + '%', top: t.y + '%' }}></span>
        ))}
      </div>

      {/* legenda ao vivo */}
      <div className="ph-caption">
        <span className="spark"><LIcons.Sparkle size={13}/></span>
        <span key={caption[0] + caption[1]}>{caption[0] ? <b>{caption[0]} </b> : null}{caption[1]}</span>
      </div>
    </div>
  );
}

Object.assign(window, { PhoneDemo });
