// ═══════════════════════════════════════════════════════════════
// FLOW — Режим Поток. Таймер 2 часа, 2x XP на все действия,
// автостоп когда время вышло.
// ═══════════════════════════════════════════════════════════════

const FlowPage = ({ flow, setFlow, profile, quests, completeQuest, logEvent }) => {
  const [now, setNow] = React.useState(Date.now());
  const [microTask, setMicroTask] = React.useState("");
  const [microTasks, setMicroTasks] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("ss_flow_micro") || "[]"); } catch { return []; }
  });
  const saveMicro = (m) => { setMicroTasks(m); localStorage.setItem("ss_flow_micro", JSON.stringify(m)); };

  const durationMs = (flow?.durationMin || 120) * 60 * 1000;
  const elapsed = flow?.active && flow?.startedAt ? now - new Date(flow.startedAt).getTime() : 0;
  const remaining = Math.max(0, durationMs - elapsed);
  const remainingMin = Math.floor(remaining / 60000);
  const remainingSec = Math.floor((remaining % 60000) / 1000);
  const progressPct = flow?.active ? Math.min(100, (elapsed / durationMs) * 100) : 0;

  // Тикаем каждую секунду
  React.useEffect(() => {
    if (!flow?.active) return;
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(t);
  }, [flow?.active]);

  // Автостоп когда время вышло
  React.useEffect(() => {
    if (flow?.active && remaining <= 0 && elapsed > 0) {
      stopFlow(true);
    }
  }, [remaining, flow?.active]);

  const startFlow = () => {
    setFlow({ ...(flow||{}), active: true, startedAt: new Date().toISOString(),
      durationMin: flow?.durationMin || 120,
      completedSessions: flow?.completedSessions || [] });
    playSound("flow_start");
    if (logEvent) logEvent("🌊 Поток активирован — XP ×2 на 2 часа", "");
  };

  const stopFlow = (auto=false) => {
    const session = {
      startedAt: flow.startedAt,
      endedAt: new Date().toISOString(),
      duration: elapsed,
      auto
    };
    setFlow({ ...flow, active: false, startedAt: null,
      completedSessions: [session, ...(flow.completedSessions||[])].slice(0, 30) });
    playSound("flow_end");
    if (logEvent) logEvent(auto ? "🏁 Поток завершён (время вышло)" : "⏸ Поток остановлен вручную", "");
  };

  const setDuration = (min) => setFlow({ ...(flow||{}), durationMin: min });

  const addMicroTask = () => {
    if (!microTask.trim()) return;
    saveMicro([{ id: "mt"+Date.now(), title: microTask.trim(), done: false }, ...microTasks]);
    setMicroTask("");
  };
  const toggleMicro = (id) => {
    saveMicro(microTasks.map(m => m.id === id ? {...m, done: !m.done} : m));
    if (flow?.active) playSound("click");
  };
  const removeMicro = (id) => saveMicro(microTasks.filter(m => m.id !== id));

  // Все активные квесты которые могут быть закрыты в потоке
  const activeQuests = (quests||[]).filter(q => !q.done && !q.daily);

  return (
    <div style={{ maxWidth: 720, margin:"0 auto", padding:"20px 16px" }}>
      <div style={{ marginBottom:20 }}>
        <div className="eyebrow">Режим концентрации</div>
        <h1 style={{ margin:"4px 0 0" }}>Поток</h1>
        <div style={{ fontSize:12, color:"var(--text-3)", marginTop:6 }}>
          Активируй таймер чтобы получать XP ×2 за все выполненные задачи
        </div>
      </div>

      {/* Главный таймер */}
      <div className="ss-card" style={{
        padding: "32px 24px", marginBottom: 16,
        textAlign: "center", position: "relative", overflow: "hidden",
        border: flow?.active ? "2px solid #60a5fa" : "1px solid var(--line-2)",
        background: flow?.active
          ? "linear-gradient(135deg, rgba(96,165,250,0.15), rgba(168,85,247,0.1))"
          : "var(--bg-4)"
      }}>
        {flow?.active && (
          <div style={{ position:"absolute", top:0, left:0, right:0, height:3, background:"var(--bg-2)" }}>
            <div style={{ height:"100%", width:`${progressPct}%`, background:"linear-gradient(90deg, #60a5fa, #a855f7)", transition:"width 1s linear" }}/>
          </div>
        )}

        <div style={{ fontSize: 14, color: flow?.active ? "#60a5fa" : "var(--text-3)", marginBottom: 8, fontWeight: 600, letterSpacing: 1 }}>
          {flow?.active ? "🌊 ПОТОК АКТИВЕН" : "Таймер не запущен"}
        </div>

        <div style={{
          fontFamily: "var(--font-display)",
          fontSize: 80, fontWeight: 700, lineHeight: 1,
          color: flow?.active ? "#fff" : "var(--text-2)",
          marginBottom: 8,
          textShadow: flow?.active ? "0 0 20px rgba(96,165,250,0.5)" : "none"
        }}>
          {flow?.active ? `${String(remainingMin).padStart(2,"0")}:${String(remainingSec).padStart(2,"0")}` : `${flow?.durationMin || 120}:00`}
        </div>

        <div style={{ fontSize:13, color:"var(--text-3)", marginBottom:20 }}>
          {flow?.active
            ? `Осталось до автостопа • XP ×2 на все действия`
            : `Длительность сессии: ${flow?.durationMin || 120} мин`}
        </div>

        {!flow?.active && (
          <div style={{ display:"flex", justifyContent:"center", gap:6, marginBottom:16, flexWrap:"wrap" }}>
            {[60, 90, 120, 150, 180].map(m => (
              <button key={m} onClick={()=>setDuration(m)}
                style={{
                  padding:"6px 14px", borderRadius:8, fontSize:12, cursor:"pointer",
                  border: (flow?.durationMin||120)===m ? "1px solid #60a5fa" : "1px solid var(--line-2)",
                  background: (flow?.durationMin||120)===m ? "rgba(96,165,250,0.15)" : "var(--bg-3)",
                  color: (flow?.durationMin||120)===m ? "#60a5fa" : "var(--text-2)"
                }}>
                {m} мин
              </button>
            ))}
          </div>
        )}

        {!flow?.active ? (
          <button onClick={startFlow}
            style={{
              padding:"14px 36px", fontSize:16, fontWeight:700,
              background:"linear-gradient(135deg, #60a5fa, #a855f7)",
              color:"white", border:"none", borderRadius:12, cursor:"pointer",
              boxShadow:"0 4px 20px rgba(96,165,250,0.4)",
              transition:"transform 0.15s"
            }}
            onMouseDown={e=>e.currentTarget.style.transform="scale(0.97)"}
            onMouseUp={e=>e.currentTarget.style.transform="scale(1)"}>
            🌊 Войти в Поток
          </button>
        ) : (
          <button onClick={()=>{ if(confirm("Остановить Поток досрочно?")) stopFlow(false); }}
            style={{
              padding:"12px 28px", fontSize:14, fontWeight:600,
              background:"rgba(220,50,50,0.15)", color:"var(--crimson)",
              border:"1px solid var(--crimson)", borderRadius:10, cursor:"pointer"
            }}>
            ⏸ Остановить
          </button>
        )}
      </div>

      {/* Микро-задачи для удержания фокуса */}
      <div className="ss-card" style={{ padding:"16px 18px", marginBottom:16 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>🎯 Микро-задачи (на эту сессию)</div>
        <div style={{ display:"flex", gap:6, marginBottom:10 }}>
          <input value={microTask} onChange={e=>setMicroTask(e.target.value)}
            onKeyDown={e=>e.key==="Enter"&&addMicroTask()}
            className="ss-input" style={{ flex:1, fontSize:13 }}
            placeholder="Напиши маленькую задачу на 5-15 минут..." />
          <button onClick={addMicroTask} className="ss-btn">+</button>
        </div>
        {microTasks.length === 0 && (
          <div style={{ fontSize:11, color:"var(--text-4)" }}>Дроби большие задачи на маленькие — это держит внимание на 99%</div>
        )}
        {microTasks.map(m => (
          <div key={m.id} style={{
            display:"flex", alignItems:"center", gap:8, padding:"6px 0",
            borderBottom:"1px solid var(--line-1)"
          }}>
            <button onClick={()=>toggleMicro(m.id)}
              style={{
                width:18, height:18, borderRadius:4, border:`2px solid ${m.done?"#4ade80":"var(--line-2)"}`,
                background: m.done ? "#4ade80" : "transparent",
                cursor:"pointer", display:"flex", alignItems:"center", justifyContent:"center",
                color:"white", fontSize:10, flexShrink:0
              }}>{m.done && "✓"}</button>
            <span style={{ flex:1, fontSize:13, color: m.done?"var(--text-3)":"var(--text-1)", textDecoration: m.done?"line-through":"none" }}>{m.title}</span>
            <button onClick={()=>removeMicro(m.id)} style={{ background:"none", border:"none", cursor:"pointer", color:"var(--text-4)", fontSize:14 }}>✕</button>
          </div>
        ))}
      </div>

      {/* Активные квесты для быстрого закрытия */}
      {activeQuests.length > 0 && (
        <div className="ss-card" style={{ padding:"16px 18px", marginBottom:16 }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>⚡ Активные квесты {flow?.active && <span style={{color:"#60a5fa"}}>(закрытие = ×2 XP)</span>}</div>
          {activeQuests.slice(0, 8).map(q => (
            <div key={q.id} style={{ display:"flex", alignItems:"center", gap:8, padding:"6px 0", borderBottom:"1px solid var(--line-1)" }}>
              <button onClick={()=>completeQuest(q.id)}
                style={{ width:20, height:20, borderRadius:5, border:"2px solid var(--accent)", background:"transparent", cursor:"pointer", flexShrink:0 }}/>
              <span style={{ flex:1, fontSize:13 }}>{q.title}</span>
              <span style={{ fontSize:11, color:"var(--accent)" }}>+{((q.xp||50) * (flow?.active?2:1))} XP</span>
            </div>
          ))}
        </div>
      )}

      {/* История сессий */}
      {flow?.completedSessions && flow.completedSessions.length > 0 && (
        <div className="ss-card" style={{ padding:"16px 18px" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>📊 Последние сессии</div>
          {flow.completedSessions.slice(0, 5).map((s, i) => {
            const dur = Math.floor(s.duration / 60000);
            return (
              <div key={i} style={{ display:"flex", justifyContent:"space-between", padding:"6px 0", fontSize:12, borderBottom:"1px solid var(--line-1)" }}>
                <span style={{ color:"var(--text-2)" }}>{new Date(s.startedAt).toLocaleString("ru",{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})}</span>
                <span style={{ color: s.auto?"#4ade80":"var(--text-3)" }}>{dur} мин {s.auto && "✓"}</span>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};
