const PreviewProfileSwitch = () => {
  const { snapshot, selectedProfile, selectProfile, busy } = useAinaApp();

  if (!snapshot?.profiles?.length || !selectedProfile) {
    return null;
  }

  return (
    <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
      {snapshot.profiles.map((profile) => {
        const who = getWhoForName(profile.name);
        const active = profile.id === selectedProfile.id;
        return (
          <button
            key={profile.id}
            onClick={() => selectProfile(profile.id).catch(() => null)}
            disabled={busy}
            style={{
              flex: 1,
              height: 38,
              borderRadius: 19,
              padding: "0 10px",
              background: active ? "rgba(255,255,255,0.96)" : "rgba(255,255,255,0.06)",
              color: active ? "#0a0612" : "#fff",
              border: active ? "none" : "0.5px solid rgba(255,255,255,0.14)",
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              gap: 8,
              fontFamily: "inherit",
              fontSize: 13,
              fontWeight: 600,
              cursor: busy ? "default" : "pointer",
              opacity: busy ? 0.7 : 1
            }}
          >
            <Avatar who={who} size={18} ring={false} />
            {profile.name}
          </button>
        );
      })}
    </div>
  );
};

const HomeScreen = ({ onOpenDiagram, onOpenNight }) => {
  const {
    snapshot,
    selectedProfile,
    viewer,
    partnerProfile,
    addHabit,
    addTask,
    toggleHabit,
    toggleTask,
    deleteHabit,
    deleteTask,
    openGoogleConnect,
    disconnectGoogle
  } = useAinaApp();
  const [extras, setExtras] = React.useState({
    habits: false,
    tasks: false,
    calendar: false
  });

  const toggle = (key) =>
    setExtras((current) => ({
      ...current,
      [key]: !current[key]
    }));

  if (!snapshot || !selectedProfile || !viewer) {
    return <LoadingState title="Home" body="Cargando tu dashboard real..." />;
  }

  const editable = Boolean(selectedProfile.isViewer);
  const selectedWho = getWhoForName(selectedProfile.name);
  const meSummary = snapshot.profiles.find((profile) => profile.id === viewer.profileId);
  const otherSummary = partnerProfile;
  const highlights = snapshot.home?.todayHighlights || [];
  const coupleGoal = snapshot.couple?.goal?.title || "Sin meta conjunta definida";
  const calendar = selectedProfile.calendar || {
    status: "not_configured",
    events: [],
    nextEventLabel: "Sin agenda sincronizada.",
    busyLabel: "0m"
  };

  const handleAddHabit = async () => {
    if (!editable) {
      return;
    }

    const title = window.prompt("Nuevo habito");
    if (!title) {
      return;
    }

    const category = window.prompt("Categoria") || "";
    await addHabit(title, category).catch(() => null);
  };

  const handleAddTask = async () => {
    if (!editable) {
      return;
    }

    const title = window.prompt("Nueva tarea");
    if (!title) {
      return;
    }

    await addTask(title).catch(() => null);
  };

  return (
    <div
      className="noscroll"
      style={{
        height: "100%",
        overflowY: "auto",
        padding: "54px 16px 110px"
      }}
    >
      <ScreenTitle
        sub={String(selectedProfile.today.label || "").toUpperCase()}
        right={
          <button
            onClick={onOpenNight}
            style={{
              width: 38,
              height: 38,
              borderRadius: 19,
              background: "rgba(255,255,255,0.08)",
              border: "0.5px solid rgba(255,255,255,0.14)",
              backdropFilter: "blur(18px)",
              color: "#fff",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              cursor: "pointer"
            }}
          >
            <I.Bell size={17} />
          </button>
        }
      >
        Hoy
      </ScreenTitle>

      <PreviewProfileSwitch />

      <Glass padding={18} radius={26} style={{ marginBottom: 12 }}>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "flex-start",
            marginBottom: 16,
            gap: 12
          }}
        >
          <div>
            <div
              style={{
                fontSize: 11,
                letterSpacing: "0.14em",
                textTransform: "uppercase",
                color: "rgba(255,255,255,0.55)"
              }}
            >
              Meta comun
            </div>
            <div
              className="serif"
              style={{
                fontSize: 22,
                lineHeight: 1.15,
                marginTop: 6,
                maxWidth: 210
              }}
            >
              {coupleGoal}
            </div>
          </div>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 5,
              padding: "5px 10px",
              borderRadius: 11,
              background: "rgba(255,255,255,0.08)",
              border: "0.5px solid rgba(255,255,255,0.14)"
            }}
          >
            <I.Flame size={13} color="oklch(0.78 0.14 50)" />
            <span style={{ fontSize: 13, fontWeight: 600 }}>
              {snapshot.couple?.jointStreakDays || 0}
            </span>
            <span
              style={{
                fontSize: 11,
                color: "rgba(255,255,255,0.55)"
              }}
            >
              dias
            </span>
          </div>
        </div>

        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-around",
            padding: "6px 0"
          }}
        >
          <div style={{ textAlign: "center" }}>
            <ScoreRing
              value={meSummary?.today.score || 0}
              who={getWhoForName(meSummary?.name)}
              size={80}
              stroke={6}
            />
            <div
              style={{
                marginTop: 8,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 6
              }}
            >
              <Avatar who={getWhoForName(meSummary?.name)} size={18} ring={false} />
              <span style={{ fontSize: 13, fontWeight: 590 }}>{meSummary?.name || "Yo"}</span>
            </div>
          </div>

          <div
            style={{
              width: 1,
              height: 80,
              background: "rgba(255,255,255,0.1)"
            }}
          />

          <div style={{ textAlign: "center" }}>
            <div style={{ position: "relative", display: "inline-block" }}>
              <div
                style={{
                  position: "absolute",
                  inset: -8,
                  borderRadius: "50%",
                  background:
                    "radial-gradient(circle, rgba(255,184,200,0.25), transparent 70%)",
                  pointerEvents: "none"
                }}
              />
              <div style={{ position: "relative" }}>
                <div
                  className="serif"
                  style={{
                    fontSize: 60,
                    lineHeight: 0.9,
                    letterSpacing: "-0.02em"
                  }}
                >
                  {snapshot.couple?.completionRate || 0}
                  <span
                    style={{
                      fontSize: 20,
                      color: "rgba(255,255,255,0.5)"
                    }}
                  >
                    %
                  </span>
                </div>
                <div
                  style={{
                    fontSize: 10,
                    letterSpacing: "0.18em",
                    textTransform: "uppercase",
                    color: "rgba(255,255,255,0.55)",
                    marginTop: 4
                  }}
                >
                  Progreso conjunto
                </div>
              </div>
            </div>
          </div>

          <div
            style={{
              width: 1,
              height: 80,
              background: "rgba(255,255,255,0.1)"
            }}
          />

          <div style={{ textAlign: "center" }}>
            <ScoreRing
              value={otherSummary?.today.score || 0}
              who={getWhoForName(otherSummary?.name)}
              size={80}
              stroke={6}
            />
            <div
              style={{
                marginTop: 8,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 6
              }}
            >
              <Avatar who={getWhoForName(otherSummary?.name)} size={18} ring={false} />
              <span style={{ fontSize: 13, fontWeight: 590 }}>
                {otherSummary?.name || "Pareja"}
              </span>
            </div>
          </div>
        </div>
      </Glass>

      <Glass padding={16} style={{ marginBottom: 12 }}>
        <SectionLabel icon={<I.Sparkle size={12} />}>Highlights · hoy</SectionLabel>
        {highlights.length ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {highlights.map((item) => (
              <div
                key={item.id}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 10
                }}
              >
                <Avatar who={getWhoForName(item.actorName)} size={26} />
                <div
                  style={{
                    flex: 1,
                    fontSize: 13,
                    lineHeight: 1.35,
                    color: "rgba(255,255,255,0.88)"
                  }}
                >
                  {item.summary}
                </div>
                <span
                  style={{
                    fontSize: 11,
                    color: "rgba(255,255,255,0.4)",
                    fontVariantNumeric: "tabular-nums"
                  }}
                >
                  {formatPreviewTime(item.createdAt)}
                </span>
              </div>
            ))}
          </div>
        ) : (
          <div
            style={{
              fontSize: 13,
              lineHeight: 1.5,
              color: "rgba(255,255,255,0.58)"
            }}
          >
            Todavia no hay movimientos guardados hoy.
          </div>
        )}
      </Glass>

      <button
        onClick={onOpenDiagram}
        style={{
          width: "100%",
          marginBottom: 12,
          padding: "14px 18px",
          background:
            "linear-gradient(135deg, rgba(255,200,170,0.18), rgba(180,150,255,0.18))",
          border: "0.5px solid rgba(255,255,255,0.18)",
          backdropFilter: "blur(20px)",
          WebkitBackdropFilter: "blur(20px)",
          borderRadius: 22,
          color: "#fff",
          display: "flex",
          alignItems: "center",
          gap: 12,
          cursor: "pointer",
          textAlign: "left"
        }}
      >
        <div
          style={{
            width: 42,
            height: 42,
            borderRadius: 12,
            background: "rgba(255,255,255,0.12)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            flexShrink: 0
          }}
        >
          <I.Compass size={22} />
        </div>
        <div style={{ flex: 1 }}>
          <div
            className="serif"
            style={{ fontSize: 18, lineHeight: 1 }}
          >
            Diagrama de la paz
          </div>
          <div
            style={{
              fontSize: 12,
              color: "rgba(255,255,255,0.6)",
              marginTop: 3
            }}
          >
            Si discutimos, que hacer
          </div>
        </div>
        <I.Chev size={18} color="rgba(255,255,255,0.55)" />
      </button>

      <ExpandableBlock
        open={extras.habits}
        onToggle={() => toggle("habits")}
        icon={<I.Bolt size={12} />}
        label={`Habitos · ${selectedProfile.name}`}
        right={
          <span style={{ color: "rgba(255,255,255,0.5)", fontSize: 12 }}>
            {selectedProfile.today.completedHabitCount} / {selectedProfile.today.habitCount}
          </span>
        }
      >
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {selectedProfile.habits.length ? (
            selectedProfile.habits.map((habit) => (
              <HabitRow
                key={habit.id}
                name={habit.title}
                done={habit.done}
                editable={editable}
                onToggle={() => toggleHabit(habit.id).catch(() => null)}
                onDelete={() => deleteHabit(habit.id).catch(() => null)}
              />
            ))
          ) : (
            <div style={{ fontSize: 13, color: "rgba(255,255,255,0.55)" }}>
              No hay habitos creados.
            </div>
          )}
          {editable ? (
            <button
              onClick={handleAddHabit}
              style={{
                marginTop: 4,
                height: 36,
                borderRadius: 12,
                background: "transparent",
                color: "rgba(255,255,255,0.6)",
                border: "0.5px dashed rgba(255,255,255,0.2)",
                fontSize: 13,
                cursor: "pointer",
                display: "inline-flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 6
              }}
            >
              <I.Plus size={14} />
              Nuevo habito
            </button>
          ) : (
            <div style={{ fontSize: 12, color: "rgba(255,255,255,0.45)" }}>
              Solo lectura: este perfil lo edita {selectedProfile.name}.
            </div>
          )}
        </div>
      </ExpandableBlock>

      <ExpandableBlock
        open={extras.tasks}
        onToggle={() => toggle("tasks")}
        icon={<I.Check size={12} />}
        label={`Tareas · ${selectedProfile.name}`}
        right={
          <span style={{ color: "rgba(255,255,255,0.5)", fontSize: 12 }}>
            {selectedProfile.today.completedTaskCount} / {selectedProfile.today.taskCount}
          </span>
        }
      >
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {selectedProfile.tasks.length ? (
            selectedProfile.tasks.map((task) => (
              <HabitRow
                key={task.id}
                name={task.title}
                done={task.done}
                task
                editable={editable}
                onToggle={() => toggleTask(task.id).catch(() => null)}
                onDelete={() => deleteTask(task.id).catch(() => null)}
              />
            ))
          ) : (
            <div style={{ fontSize: 13, color: "rgba(255,255,255,0.55)" }}>
              No hay tareas guardadas.
            </div>
          )}
          {editable ? (
            <button
              onClick={handleAddTask}
              style={{
                marginTop: 4,
                height: 36,
                borderRadius: 12,
                background: "transparent",
                color: "rgba(255,255,255,0.6)",
                border: "0.5px dashed rgba(255,255,255,0.2)",
                fontSize: 13,
                cursor: "pointer",
                display: "inline-flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 6
              }}
            >
              <I.Plus size={14} />
              Nueva tarea
            </button>
          ) : (
            <div style={{ fontSize: 12, color: "rgba(255,255,255,0.45)" }}>
              Solo lectura: estas viendo las tareas de {selectedProfile.name}.
            </div>
          )}
        </div>
      </ExpandableBlock>

      <ExpandableBlock
        open={extras.calendar}
        onToggle={() => toggle("calendar")}
        icon={<I.Cal size={12} />}
        label={`Agenda · ${selectedProfile.name}`}
        right={
          <span
            style={{
              color:
                calendar.status === "connected"
                  ? "oklch(0.78 0.14 150)"
                  : "rgba(255,255,255,0.55)",
              fontSize: 11,
              fontWeight: 590
            }}
          >
            {calendar.status === "connected" ? "Conectado" : "Sin conectar"}
          </span>
        }
      >
        {calendar.events?.length ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {calendar.events.map((event) => (
              <div
                key={event.id}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 12,
                  padding: "8px 4px"
                }}
              >
                <div
                  style={{
                    width: 4,
                    height: 28,
                    borderRadius: 2,
                    background: selectedWho === "aina" ? AINA.a : AINA.v
                  }}
                />
                <div
                  style={{
                    width: 74,
                    fontSize: 13,
                    fontVariantNumeric: "tabular-nums",
                    color: "rgba(255,255,255,0.85)"
                  }}
                >
                  {event.timeLabel}
                </div>
                <div style={{ flex: 1, fontSize: 14 }}>{event.title}</div>
              </div>
            ))}
          </div>
        ) : (
          <div style={{ fontSize: 13, lineHeight: 1.55, color: "rgba(255,255,255,0.65)" }}>
            {calendar.nextEventLabel}
          </div>
        )}
        {editable && (
          <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
            {calendar.status === "connected" ? (
              <PillBtn ghost onClick={() => disconnectGoogle().catch(() => null)} style={{ flex: 1 }}>
                Desconectar
              </PillBtn>
            ) : (
              <PillBtn primary onClick={() => openGoogleConnect().catch(() => null)} style={{ flex: 1 }}>
                Conectar Google
              </PillBtn>
            )}
          </div>
        )}
      </ExpandableBlock>

      <div
        style={{
          marginTop: 14,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 8,
          fontSize: 11,
          color: "rgba(255,255,255,0.45)"
        }}
      >
        <I.Wifi size={12} />
        <span>Sincronizado · {formatPreviewTime(snapshot.generatedAt) || "ahora"}</span>
      </div>
    </div>
  );
};

const ExpandableBlock = ({ open, onToggle, icon, label, right, children }) => (
  <Glass soft padding={14} style={{ marginBottom: 10 }}>
    <button
      onClick={onToggle}
      style={{
        width: "100%",
        background: "none",
        border: 0,
        color: "#fff",
        padding: 0,
        cursor: "pointer",
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between"
      }}
    >
      <div
        style={{
          fontSize: 11,
          fontWeight: 590,
          letterSpacing: "0.14em",
          textTransform: "uppercase",
          color: "rgba(255,255,255,0.7)",
          display: "inline-flex",
          alignItems: "center",
          gap: 6
        }}
      >
        {icon}
        {label}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        {right}
        <div
          style={{
            transition: "transform 0.25s ease",
            transform: open ? "rotate(180deg)" : "rotate(0deg)",
            color: "rgba(255,255,255,0.55)"
          }}
        >
          <I.Down size={16} />
        </div>
      </div>
    </button>
    {open && <div style={{ marginTop: 14 }}>{children}</div>}
  </Glass>
);

const HabitRow = ({ name, done, task, editable, onToggle, onDelete }) => (
  <div
    style={{
      display: "flex",
      alignItems: "center",
      gap: 12
    }}
  >
    <button
      onClick={editable ? onToggle : undefined}
      style={{
        flex: 1,
        display: "flex",
        alignItems: "center",
        gap: 12,
        padding: "6px 4px",
        background: "transparent",
        border: 0,
        cursor: editable ? "pointer" : "default",
        color: "#fff",
        textAlign: "left"
      }}
    >
      <div
        style={{
          width: 24,
          height: 24,
          borderRadius: task ? 7 : 12,
          border: `1.5px solid ${done ? "transparent" : "rgba(255,255,255,0.3)"}`,
          background: done ? "#fff" : "transparent",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          flexShrink: 0
        }}
      >
        {done && <I.Check size={14} color="#0a0612" />}
      </div>
      <span
        style={{
          flex: 1,
          fontSize: 14,
          textDecoration: done && task ? "line-through" : "none",
          opacity: done ? 0.55 : 1
        }}
      >
        {name}
      </span>
    </button>
    {editable && (
      <button
        onClick={onDelete}
        style={{
          width: 28,
          height: 28,
          borderRadius: 14,
          border: "0.5px solid rgba(255,255,255,0.18)",
          background: "rgba(255,255,255,0.04)",
          color: "rgba(255,255,255,0.72)",
          cursor: "pointer"
        }}
      >
        ×
      </button>
    )}
  </div>
);

window.HomeScreen = HomeScreen;
