/* global React, LIcons */
// Como funciona — cena animada: USB conecta → contas detectadas → iniciar aquecimento (loop)

const { useState: useScState, useEffect: useScEffect, useRef: useScRef } = React;

const SC_STEPS = [
  { title: 'Conecte via USB', desc: 'Plugue o celular no PC. Sem API, sem senha — o controle é físico.', dur: 4600 },
  { title: 'Contas detectadas', desc: 'O painel encontra o aparelho e lista as contas prontas para aquecer.', dur: 4200 },
  { title: 'Inicie o aquecimento', desc: 'Um clique e as interações rodam sozinhas — de dia, de noite, no loop.', dur: 8400 },
];

const SC_LOGS = [
  ['@loja.doce.rj', 'curtiu um vídeo'],
  ['@fit.gabi', 'assistiu 14s de vídeo'],
  ['@viral.cortes', 'comentou em um vídeo'],
  ['@loja.doce.rj', 'salvou um vídeo'],
  ['@fit.gabi', 'compartilhou um vídeo'],
];

function StepsSection() {
  const [step, setStep] = useScState(0);
  const [cycle, setCycle] = useScState(0);
  const [sc, setSc] = useScState({});
  const [cursor, setCursor] = useScState({ x: 480, y: 330, vis: false });
  const [click, setClick] = useScState(0);
  const [log, setLog] = useScState(0);
  const timers = useScRef([]);

  const after = (ms, fn) => timers.current.push(setTimeout(fn, ms));
  const clearAll = () => { timers.current.forEach(clearTimeout); timers.current = []; };

  // timeline por passo
  useScEffect(() => {
    clearAll();
    if (step === 0) {
      setSc({}); setCursor(c => ({ ...c, vis: false }));
      after(700, () => setSc({ plugged: true }));
      after(1500, () => setSc({ plugged: true, flowing: true }));
    } else if (step === 1) {
      setSc(s => ({ plugged: true, flowing: true, detected: true }));
      setCursor(c => ({ ...c, vis: false }));
    } else {
      setSc(s => ({ ...s, plugged: true, flowing: true, detected: true }));
      setCursor({ x: 480, y: 330, vis: true });
      after(500, () => setCursor({ x: 408, y: 296, vis: true }));
      after(1300, () => { setClick(c => c + 1); setSc(s => ({ ...s, pressing: true })); });
      after(1550, () => setSc(s => ({ ...s, pressing: false, running: true })));
      after(2100, () => setCursor(c => ({ ...c, x: 470, y: 345 })));
      after(3000, () => setCursor(c => ({ ...c, vis: false })));
    }
    // auto-avança
    after(SC_STEPS[step].dur, () => {
      setStep(s => (s + 1) % 3);
      setCycle(c => c + 1);
    });
    return clearAll;
  }, [step, cycle]);

  // logs em loop enquanto rodando
  useScEffect(() => {
    if (!sc.running) return;
    const id = setInterval(() => setLog(l => l + 1), 2000);
    return () => clearInterval(id);
  }, [sc.running]);

  // escala da cena
  const wrapRef = useScRef(null);
  const [scale, setScale] = useScState(1);
  useScEffect(() => {
    const fit = () => {
      if (!wrapRef.current) return;
      const w = wrapRef.current.clientWidth - 24;
      setScale(Math.min(1, w / 620));
    };
    fit();
    window.addEventListener('resize', fit);
    return () => window.removeEventListener('resize', fit);
  }, []);

  const lg = SC_LOGS[log % SC_LOGS.length];
  const scClass = ['sc', sc.plugged && 'plugged', sc.flowing && 'flowing', sc.detected && 'detected', sc.pressing && 'pressing', sc.running && 'running'].filter(Boolean).join(' ');

  return (
    <div className="steps-grid">
      <div className="steps-list">
        {SC_STEPS.map((s, i) => (
          <button key={i} className={`step-item ${step === i ? 'on' : ''}`}
            onClick={() => { setStep(i); setCycle(c => c + 1); }}>
            <span className="step-num">{String(i + 1).padStart(2, '0')}</span>
            <span>
              <span className="step-title" style={{ display: 'block' }}>{s.title}</span>
              <span className="step-desc">{s.desc}</span>
            </span>
            <span className="step-bar">
              {step === i && <i key={`${step}-${cycle}`} style={{ animationDuration: SC_STEPS[i].dur + 'ms' }}></i>}
            </span>
          </button>
        ))}
      </div>

      <div className="stage" ref={wrapRef}>
        <div className="stage-scale" style={{ transform: `scale(${scale})` }}>
          <div className={scClass}>
            {/* cabo usb */}
            <svg className="sc-cable" viewBox="0 0 620 380">
              <g style={{ transition: 'transform 900ms var(--ease)', transform: sc.plugged ? 'translateY(0)' : 'translateY(52px)' }}>
                <path d="M 85 316 C 85 372, 150 396, 240 396 L 420 396" />
                <path className="flow" d="M 85 316 C 85 372, 150 396, 240 396 L 420 396" />
                <rect x="78" y="298" width="14" height="24" rx="4" fill="#4a4238" stroke="#55493a" />
              </g>
            </svg>

            {/* celular */}
            <div className={`sc-phone ${sc.plugged ? 'connected' : ''}`}>
              <div className="sc-phone-screen">
                <div className="sc-phone-off"><LIcons.Usb size={22}/></div>
                <div className="sc-phone-on">
                  <span className="sc-usb-icon"><LIcons.Check size={20}/></span>
                  <span className="sc-phone-label">USB conectado<br/>Motorola G53</span>
                </div>
              </div>
              <div className="sc-phone-port"></div>
            </div>

            {/* painel */}
            <div className="sc-panel">
              <div className="sc-panel-bar">
                <span className="d"></span><span className="d"></span><span className="d"></span>
                <span className="ttl">aqueceai.pro — painel</span>
                <span className="sc-live"><span className="dot"></span>LIVE</span>
              </div>
              <div className="sc-panel-body">
                <div className="sc-device">
                  <span className="sc-device-ic"><LIcons.Phone size={15}/></span>
                  <span>
                    <span className="sc-device-name" style={{ display: 'block' }}>Motorola G53</span>
                    <span className="sc-device-sub">USB · Android 13</span>
                  </span>
                  <span className="sc-device-status">{sc.plugged ? 'conectado' : 'aguardando...'}</span>
                </div>

                <div className="sc-accs">
                  {['@loja.doce.rj', '@fit.gabi', '@viral.cortes'].map((h, i) => (
                    <div className="sc-acc" key={h}>
                      <span className="sc-acc-num">{i + 1}</span>
                      <span className="sc-acc-handle">{h}</span>
                      <span className="sc-acc-badge">{sc.running ? 'aquecendo' : 'pronta'}</span>
                    </div>
                  ))}
                </div>

                <div className="sc-start">
                  {sc.running
                    ? <React.Fragment><LIcons.Flame size={15}/> Aquecendo 3 contas...</React.Fragment>
                    : <React.Fragment><LIcons.Play size={15}/> Iniciar aquecimento</React.Fragment>}
                </div>

                <div className="sc-log">
                  <span className="spark"><LIcons.Sparkle size={13}/></span>
                  {sc.running && <span className="sc-log-msg" key={log}><b>{lg[0]}</b> {lg[1]}</span>}
                </div>
              </div>
            </div>

            {/* cursor */}
            <span className="sc-cursor" style={{ left: cursor.x, top: cursor.y, opacity: cursor.vis ? 1 : 0 }}>
              <LIcons.Cursor size={20}/>
            </span>
            {click > 0 && <span className="sc-click" key={click} style={{ left: 414, top: 302 }}></span>}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { StepsSection });
