// ─────────────────────────────────────────────────────────────
// ABA HÁBITOS — Tracker semanal editorial
// Grade 7 dias × 5 hábitos. Toque para marcar.
// Persistente em localStorage.
// ─────────────────────────────────────────────────────────────

const { useState, useEffect } = React;

// ── HÁBITOS PADRÃO ───────────────────────────────────────────
// EDITAR: se quiser trocar/adicionar hábito, mexer aqui
// label = nome curto que aparece na GRADE (pra caber sem quebrar feio)
// resumo = nome completo que aparece no RESUMO de baixo (cai pro label se vazio)
const HABITOS_DEFAULT = [
  { id: "oracao",   label: "Oração / Meditação",        resumo: "Oração / Meditação" },
  { id: "treino",   label: "Treinos",                   resumo: "Treinos de força" },
  { id: "estudo",   label: "Estudar / Trabalhar",       resumo: "Estudar / Trabalhar" },
  { id: "sol",      label: "Sol",                       resumo: "Sol 30 minutos" },
  { id: "suple",    label: "Suplementos / Manipulados", resumo: "Suplementos / Manipulados" },
  { id: "agua",     label: "Água",                      resumo: "Água" },
  { id: "cardio",   label: "Cardio",                    resumo: "Cardio 35 minutos" },
  { id: "ajudar",   label: "Ajudar alguém",             resumo: "Ajudar alguém" },
  { id: "sono",     label: "Sono",                      resumo: "Sono 7 a 9 horas" },
];

const DIAS_SEMANA = ["DOM","SEG","TER","QUA","QUI","SEX","SÁB"]; // Dom a Sáb

// pega o DOMINGO da semana atual no formato YYYY-MM-DD (semana começa no domingo)
function getMondayISO(d = new Date()) {
  const x = new Date(d);
  const day = x.getDay(); // 0=dom, 1=seg ... 6=sáb
  x.setDate(x.getDate() - day); // recua até o domingo
  x.setHours(0,0,0,0);
  return x.toISOString().slice(0,10);
}

function addDaysISO(iso, n) {
  const d = new Date(iso + "T00:00:00");
  d.setDate(d.getDate() + n);
  return d.toISOString().slice(0,10);
}

function HabitosScreen({ t, onBack, onIniciarAnalise }) {
  // estado: { 'YYYY-MM-DD': ['sono','treino'] }
  const [data, setData] = useState(() => {
    try { return JSON.parse(localStorage.getItem("habitos_v1") || "{}"); }
    catch { return {}; }
  });
  useEffect(() => {
    localStorage.setItem("habitos_v1", JSON.stringify(data));
  }, [data]);

  const [weekStart, setWeekStart] = useState(() => getMondayISO());

  // gaveta do tracker de hábitos (fechada por padrão)
  const [trackerOpen, setTrackerOpen] = useState(false);

  const dias = Array.from({ length: 7 }, (_, i) => addDaysISO(weekStart, i));
  const hoje = new Date().toISOString().slice(0, 10);

  const isDone = (dia, hab) => (data[dia] || []).includes(hab);
  const toggle = (dia, hab) => {
    setData((d) => {
      const arr = d[dia] || [];
      const next = arr.includes(hab) ? arr.filter(x => x !== hab) : [...arr, hab];
      return { ...d, [dia]: next };
    });
  };

  // hábitos ativos/inativos — o usuário liga/desliga o que NÃO faz parte da rotina dele
  const [inativos, setInativos] = useState(() => {
    try { return new Set(JSON.parse(localStorage.getItem("habitos_inativos_v1") || "[]")); }
    catch { return new Set(); }
  });
  useEffect(() => {
    localStorage.setItem("habitos_inativos_v1", JSON.stringify([...inativos]));
  }, [inativos]);
  const isAtivo = (id) => !inativos.has(id);
  const toggleAtivo = (id) => setInativos((prev) => {
    const n = new Set(prev);
    if (n.has(id)) n.delete(id); else n.add(id);
    return n;
  });

  // resumo semanal (contagem simples de marcações na semana exibida)
  const totaisSemana = HABITOS_DEFAULT.map((h) => ({
    ...h,
    ativo: isAtivo(h.id),
    done: dias.filter(d => isDone(d, h.id)).length,
  }));

  const ativosCount = totaisSemana.filter(x => x.ativo).length;
  const totalCelulas = ativosCount * 7;
  const feitas = totaisSemana.filter(x => x.ativo).reduce((s, x) => s + x.done, 0);
  const pct = totalCelulas ? Math.round((feitas / totalCelulas) * 100) : 0;

  // navegação semanal
  const prevWeek = () => setWeekStart((w) => addDaysISO(w, -7));
  const nextWeek = () => setWeekStart((w) => addDaysISO(w, 7));
  const goToday  = () => setWeekStart(getMondayISO());

  // label da semana
  const fmt = (iso) => {
    const d = new Date(iso + "T00:00:00");
    return `${String(d.getDate()).padStart(2,"0")}/${String(d.getMonth()+1).padStart(2,"0")}`;
  };
  const weekLabel = `${fmt(dias[0])} a ${fmt(dias[6])}`;

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: t.bg0, color: t.ink1,
      paddingTop: 56, paddingBottom: 100,
      overflowY: "auto", overflowX: "hidden",
      WebkitOverflowScrolling: "touch",
    }}>
      {/* TOPO STICKY — voltar pra vitrine */}
      <div style={{
        position: "sticky", top: 0, zIndex: 20,
        background: t.bg0,
        backdropFilter: "blur(20px)", WebkitBackdropFilter: "blur(20px)",
        padding: "10px 14px 12px",
        borderBottom: `1px solid ${t.border}`,
        display: "flex", alignItems: "center", gap: 12,
        boxShadow: `0 6px 16px ${t.bg0}`,
      }}>
        {onBack && (
          <button onClick={onBack} style={{
            flexShrink: 0,
            width: 38, height: 38, borderRadius: 999,
            background: t.bg1, border: `1px solid ${t.border}`,
            display: "flex", alignItems: "center", justifyContent: "center",
            color: t.ink2, cursor: "pointer",
          }}>
            <Icon name="back" size={16} stroke="currentColor" />
          </button>
        )}
        <span style={{
          fontFamily: TYPE.sans, fontSize: 10, color: t.ink3,
          letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 700,
        }}>Hábitos · Grátis</span>
      </div>

      {/* HEADER */}
      <div style={{ padding: "24px 24px 16px" }}>
        <h1 style={{
          fontFamily: TYPE.display, fontSize: 46, lineHeight: 0.95, color: t.ink1,
          letterSpacing: "-0.01em", margin: "0 0 14px", textTransform: "uppercase",
        }}>Minha<br/>Rotina</h1>
        <p style={{
          fontFamily: TYPE.sans, fontSize: 13.5, color: t.ink2, lineHeight: 1.6,
          margin: "0 0 10px", maxWidth: "94%",
        }}>
          Estes são meus hábitos diários. Não sei se é segunda ou domingo, apenas sigo minha vida.
        </p>
        <p style={{
          fontFamily: TYPE.sans, fontSize: 12.5, color: t.ink3, lineHeight: 1.55,
          margin: 0, maxWidth: "94%", fontWeight: 600,
        }}>
          Toque para marcar o que você também cumpre!
        </p>
      </div>

      {/* BOTÃO HÁBITOS — abre a gaveta do tracker (grátis) */}
      <div style={{ padding: "4px 16px 4px" }}>
        <button
          onClick={() => setTrackerOpen((o) => !o)}
          style={{
            display: "flex", alignItems: "center", gap: 14,
            width: "100%", padding: "18px 20px",
            background: trackerOpen ? t.bg2 : t.bg1,
            color: t.ink1, border: `1px solid ${trackerOpen ? t.borderStrong : t.border}`,
            borderRadius: RADIUS.md, cursor: "pointer",
            fontFamily: TYPE.sans, textAlign: "left",
            transition: "background .15s ease, border-color .15s ease",
          }}
        >
          <span style={{
            flexShrink: 0, width: 42, height: 42, borderRadius: 999,
            border: `1.5px solid ${t.border}`, color: t.ink2,
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><path d="m15 18 2 2 4-4"/>
            </svg>
          </span>
          <span style={{ flex: 1, minWidth: 0 }}>
            <span style={{
              display: "block", fontSize: 15, fontWeight: 800, letterSpacing: "0.06em",
              textTransform: "uppercase", lineHeight: 1.1,
            }}>Hábitos</span>
            <span style={{
              display: "block", marginTop: 3, fontSize: 10.5, fontWeight: 700,
              letterSpacing: "0.12em", textTransform: "uppercase", color: t.ink3, lineHeight: 1.2,
            }}>Ferramenta grátis · Marque seu dia</span>
          </span>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
            style={{ flexShrink: 0, color: t.ink3, transform: trackerOpen ? "rotate(180deg)" : "none", transition: "transform .2s ease" }}>
            <path d="m6 9 6 6 6-6"/>
          </svg>
        </button>
      </div>

      {/* GAVETA DO TRACKER */}
      {trackerOpen && (
      <div className="ana-fade-h">

      {/* PROGRESSO DA SEMANA */}
      <div style={{
        margin: "12px 16px 18px",
        padding: "18px 20px",
        background: t.bg1, border: `1px solid ${t.border}`,
        borderRadius: RADIUS.lg,
      }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 12 }}>
          <span style={{
            fontFamily: TYPE.sans, fontSize: 10, color: t.ink3,
            letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 700,
          }}>Progresso da semana</span>
          <span style={{
            fontFamily: TYPE.display, fontSize: 28, color: t.ink1,
            letterSpacing: "-0.01em", lineHeight: 1, fontVariantNumeric: "tabular-nums",
          }}>{pct}<span style={{ fontSize: 14, color: t.ink3, marginLeft: 4 }}>%</span></span>
        </div>
        <div style={{ height: 4, background: t.bg2, borderRadius: 2, overflow: "hidden" }}>
          <div style={{
            width: `${pct}%`, height: "100%", background: t.accent,
            transition: "width 0.3s ease",
          }}></div>
        </div>
        <div style={{
          marginTop: 10,
          fontFamily: TYPE.sans, fontSize: 11.5, color: t.ink3, lineHeight: 1.5,
        }}>
          {feitas} de {totalCelulas} marcações nesta semana.
        </div>
      </div>

      {/* NAVEGAÇÃO SEMANAL */}
      <div style={{
        margin: "0 16px 12px",
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <button onClick={prevWeek} style={navBtnStyle(t)}>
          <Icon name="back" size={14} stroke="currentColor" />
        </button>
        <button onClick={goToday} style={{
          background: "transparent", border: "none", cursor: "pointer",
          fontFamily: TYPE.sans, fontSize: 11, color: t.ink2,
          letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 700,
          padding: "6px 14px",
        }}>
          {weekLabel}
        </button>
        <button onClick={nextWeek} style={navBtnStyle(t)}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="m9 6 6 6-6 6"/></svg>
        </button>
      </div>

      {/* GRADE 7 × 5 */}
      <div style={{
        margin: "0 16px 18px",
        background: t.bg1, border: `1px solid ${t.border}`,
        borderRadius: RADIUS.lg, overflow: "hidden",
      }}>
        {/* cabeçalho de dias */}
        <div style={{
          display: "grid",
          gridTemplateColumns: "118px repeat(7, 1fr)",
          background: t.bg2,
          borderBottom: `1px solid ${t.border}`,
        }}>
          <div></div>
          {dias.map((iso, i) => {
            const isToday = iso === hoje;
            return (
              <div key={iso} style={{
                padding: "10px 0 8px", textAlign: "center",
                fontFamily: TYPE.sans, fontSize: 9.5,
                color: isToday ? t.accent : t.ink3, fontWeight: 700,
                letterSpacing: "0.08em", textTransform: "uppercase",
                borderLeft: i === 0 ? "none" : `1px solid ${t.border}`,
              }}>
                <div>{DIAS_SEMANA[i]}</div>
                <div style={{
                  marginTop: 3, fontSize: 11,
                  color: isToday ? t.ink1 : t.ink2,
                  fontFamily: TYPE.display, letterSpacing: 0,
                  fontVariantNumeric: "tabular-nums",
                }}>{iso.slice(8,10)}</div>
              </div>
            );
          })}
        </div>

        {/* linhas de hábitos */}
        {HABITOS_DEFAULT.map((h, hi) => {
          const ativo = isAtivo(h.id);
          return (
          <div key={h.id} style={{
            display: "grid",
            gridTemplateColumns: "118px repeat(7, 1fr)",
            borderTop: hi === 0 ? "none" : `1px solid ${t.border}`,
            opacity: ativo ? 1 : 0.42,
            transition: "opacity 0.15s ease",
          }}>
            <button
              onClick={() => toggleAtivo(h.id)}
              title={ativo ? "Desativar (sai da conta)" : "Ativar (entra na conta)"}
              style={{
                padding: "10px 10px 10px 12px", textAlign: "left", cursor: "pointer",
                background: "transparent", border: "none",
                borderRight: `1px solid ${t.border}`,
                display: "flex", alignItems: "center", gap: 8, minHeight: 56,
                fontFamily: TYPE.sans, WebkitTapHighlightColor: "transparent",
              }}
            >
              <span style={{
                flexShrink: 0, width: 9, height: 9, borderRadius: "50%",
                background: ativo ? t.ink1 : "transparent",
                border: `1.5px solid ${ativo ? t.ink1 : t.ink4}`,
              }}></span>
              <span style={{
                fontSize: 11, fontWeight: 600, lineHeight: 1.25,
                color: ativo ? t.ink1 : t.ink3,
                wordBreak: "break-word", hyphens: "none",
              }}>{h.label}</span>
            </button>
            {dias.map((iso, i) => {
              const done = isDone(iso, h.id);
              const isToday = iso === hoje;
              return (
                <button
                  key={iso}
                  disabled={!ativo}
                  onClick={() => ativo && toggle(iso, h.id)}
                  style={{
                    padding: "12px 0", cursor: ativo ? "pointer" : "default",
                    background: (done && ativo) ? t.accent : "transparent",
                    border: "none",
                    borderLeft: i === 0 ? "none" : `1px solid ${t.border}`,
                    display: "flex", alignItems: "center", justifyContent: "center",
                    minHeight: 56,
                    transition: "background 0.15s ease",
                    position: "relative",
                  }}
                >
                  {(done && ativo) ? (
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={t.accentInk} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                      <path d="m5 12 5 5 9-11"></path>
                    </svg>
                  ) : (
                    <span style={{
                      width: 6, height: 6, borderRadius: "50%",
                      background: t.border,
                    }}></span>
                  )}
                </button>
              );
            })}
          </div>
          );
        })}
      </div>

      {/* RESUMO POR HÁBITO */}
      <div style={{ padding: "0 24px 12px" }}>
        <div style={{
          fontFamily: TYPE.sans, fontSize: 10, color: t.ink3,
          letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 700,
          marginBottom: 12,
        }}>Resumo da semana</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {totaisSemana.filter(h => h.ativo).map((h) => (
            <div key={h.id} style={{
              display: "flex", gap: 16, alignItems: "center", justifyContent: "space-between",
              padding: "14px 16px",
              background: t.bg1, border: `1px solid ${t.border}`,
              borderRadius: RADIUS.md,
            }}>
              <div style={{
                fontFamily: TYPE.sans, fontSize: 13.5, color: t.ink1, fontWeight: 600,
              }}>{h.resumo || h.label}</div>
              <div style={{
                fontFamily: TYPE.display, fontSize: 18, color: h.done > 0 ? t.ink1 : t.ink4,
                letterSpacing: "-0.005em", lineHeight: 1, fontVariantNumeric: "tabular-nums",
                whiteSpace: "nowrap", flexShrink: 0,
              }}>{h.done}<span style={{ fontSize: 12, color: t.ink3 }}>/7</span></div>
            </div>
          ))}
        </div>
      </div>

      {/* RODAPÉ */}
      <div style={{
        padding: "20px 24px",
        fontFamily: TYPE.sans, fontSize: 11, color: t.ink3, lineHeight: 1.55,
        textAlign: "center",
      }}>
        Salvo automaticamente no seu dispositivo.
      </div>

      </div>
      )}
      {/* fim da gaveta do tracker */}

      {/* CTA ANÁLISE DE COMPORTAMENTO — depois do botão Hábitos */}
      {onIniciarAnalise && (
        <div style={{ padding: "4px 16px 8px" }}>
          <button
            onClick={onIniciarAnalise}
            className="cta-agendar"
            style={{
              position: "relative", overflow: "hidden",
              display: "flex", alignItems: "center", gap: 14,
              width: "100%", padding: "18px 20px",
              background: t.ink1, color: t.bg0,
              border: "none", borderRadius: RADIUS.md, cursor: "pointer",
              fontFamily: TYPE.sans, textAlign: "left",
              boxShadow: "0 10px 28px rgba(0,0,0,0.4)",
            }}
          >
            <span style={{
              flexShrink: 0, width: 42, height: 42, borderRadius: 999,
              border: `1.5px solid ${t.bg0}`, opacity: 0.9,
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
                <path d="M3 3v18h18"/><path d="m7 14 4-4 3 3 5-6"/>
              </svg>
            </span>
            <span style={{ flex: 1, minWidth: 0 }}>
              <span style={{
                display: "block", fontSize: 15, fontWeight: 800, letterSpacing: "0.06em",
                textTransform: "uppercase", lineHeight: 1.1,
              }}>Iniciar Análise de Comportamento</span>
              <span style={{
                display: "block", marginTop: 3, fontSize: 10.5, fontWeight: 700,
                letterSpacing: "0.12em", textTransform: "uppercase", opacity: 0.72, lineHeight: 1.2,
              }}>Ferramenta exclusiva para seguidores</span>
            </span>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, opacity: 0.8 }}><path d="m9 6 6 6-6 6"/></svg>
            <span aria-hidden="true" className="cta-sheen"></span>
          </button>
        </div>
      )}
    </div>
  );
}

function navBtnStyle(t) {
  return {
    width: 36, height: 36, borderRadius: 999,
    background: t.bg1, border: `1px solid ${t.border}`,
    color: t.ink2, cursor: "pointer",
    display: "flex", alignItems: "center", justifyContent: "center",
  };
}

Object.assign(window, { HabitosScreen });
