// Yomee — Profile Screen ("Mi perfil")
// Entered from the avatar in the Radiografía header. Covers RF-033 → RF-038:
//   • Mi información        (RF-033)
//   • Notificaciones        (RF-034)
//   • Privacidad y seguridad (RF-035)
//   • Mi suscripción        (RF-036)
//   • Términos y privacidad (RF-037)
//   • Cerrar sesión         (RF-038)
//
// Uses the project's existing design tokens (var(--yo-*) + Onest/Geist Mono).
// Profile chip colors map to the 4 personas already defined elsewhere
// (Totalero / Optimizador / Escalador / Reiniciador).
//
// All sub-screens (suscripción, info, notificaciones, privacidad, legales)
// live in this same file as small inner views, switched via local state.
// They share a single PageShell with a sticky back-header.
/* global React, RadioIcon, useYomeeUser, BottomSheetModal, TERMS_BODY, PRIVACY_BODY, AyudaScreen */

const { useState: useStatePF, useEffect: useEffectPF } = React;

// Body background — matches Radiografía body so the transition feels seamless.
const PF_BG = "rgb(238, 235, 230)";
const PF_FG = "var(--yo-ink)";
const PF_FG_MUTED = "#6b6b6b";
const PF_FG_SOFT = "#9aa0a6";
const PF_LINE = "rgba(20,32,28,0.08)";
const PF_BRAND = "var(--yo-forest-700)";   // #19553e — primary brand action
const PF_DANGER = "var(--yo-red-strong)";  // #dc4046 — destructive
const PF_IVORY = "#fbf7ee";                 // upgrade / privacy banner

// Profile chip colors — match RADIO_HEADER from RadiografiaScreen.jsx
const PROFILE_CHIP = {
  totalero:    { bg: "#1a6b3f", label: "Totalero"    },
  optimizador: { bg: "#185fa5", label: "Optimizador" },
  escalador:   { bg: "#7c2d12", label: "Escalador"   },
  reiniciador: { bg: "#4c1d95", label: "Reiniciador" },
};

// Subscription tiers per persona (mocked).
const TIER_BY_PERSONA = {
  ana:    { tier: "Free", price: null,            cta: "Mejora tu plan" },
  luis:   { tier: "Plus", price: "$99 MXN/mes",   cta: null },
  carlos: { tier: "Free", price: null,            cta: "Mejora tu plan" },
  sofia:  { tier: "Pro",  price: "$199 MXN/mes",  cta: null },
};

// ────────────────────────────────────────────────────────────────────
// Reusable building blocks (scoped to this file so they don't collide)
// ────────────────────────────────────────────────────────────────────

function PFAvatar({ initials, size = 64, fontSize = 22, bg }) {
  return (
    <span
      aria-hidden="true"
      style={{
        width: size,
        height: size,
        borderRadius: "50%",
        background: bg,
        color: "#fff",
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        fontFamily: "var(--font-mono)",
        fontWeight: 700,
        fontSize,
        letterSpacing: "0.02em",
        flexShrink: 0,
      }}
    >
      {initials}
    </span>
  );
}

function PFCard({ children, style }) {
  return (
    <section
      style={{
        background: "#fff",
        borderRadius: 14,
        border: "1px solid #eeeeee",
        boxShadow: "0 1px 2px rgba(20,32,28,0.04)",
        ...style,
      }}
    >
      {children}
    </section>
  );
}

// Section row — icon + title (+ optional subtitle) + chevron.
function PFRow({ icon, title, subtitle, subtitleColor, onClick, last, danger }) {
  const [pressed, setPressed] = useStatePF(false);
  return (
    <button
      type="button"
      onClick={onClick}
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
      onMouseLeave={() => setPressed(false)}
      onTouchStart={() => setPressed(true)}
      onTouchEnd={() => setPressed(false)}
      style={{
        display: "flex",
        alignItems: "center",
        gap: 14,
        width: "100%",
        padding: "14px 16px",
        background: pressed ? "#f5f5f5" : "transparent",
        border: "none",
        borderBottom: last ? "none" : `1px solid ${PF_LINE}`,
        cursor: "pointer",
        textAlign: "left",
        transition: "background 100ms ease-out",
        fontFamily: "inherit",
      }}
    >
      <span
        aria-hidden="true"
        style={{
          width: 24,
          height: 24,
          flexShrink: 0,
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          color: danger ? PF_DANGER : PF_FG,
        }}
      >
        {icon}
      </span>
      <span style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 2 }}>
        <span
          style={{
            fontFamily: "var(--font-body)",
            fontSize: 14,
            fontWeight: 500,
            color: danger ? PF_DANGER : PF_FG,
            letterSpacing: "0.005em",
            lineHeight: 1.3,
          }}
        >
          {title}
        </span>
        {subtitle && (
          <span
            style={{
              fontFamily: "var(--font-body)",
              fontSize: 12,
              fontWeight: 400,
              color: subtitleColor || PF_FG_MUTED,
              letterSpacing: "0.005em",
              lineHeight: 1.4,
            }}
          >
            {subtitle}
          </span>
        )}
      </span>
      <RadioIcon name="chevron-right" stroke={PF_FG_SOFT} size={18} />
    </button>
  );
}

// Sticky header with back arrow + title.
function PFHeader({ title, onBack }) {
  return (
    <div
      style={{
        position: "sticky",
        top: 0,
        zIndex: 5,
        background: PF_BG,
        padding: "62px 8px 12px",
        display: "grid",
        gridTemplateColumns: "44px 1fr 44px",
        alignItems: "center",
        flexShrink: 0,
      }}
    >
      <button
        type="button"
        onClick={onBack}
        aria-label="Regresar"
        style={{
          width: 44,
          height: 44,
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          background: "transparent",
          border: "none",
          padding: 0,
          cursor: "pointer",
          color: PF_FG,
        }}
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <path d="M15 18l-6-6 6-6" />
        </svg>
      </button>
      <h1
        style={{
          margin: 0,
          textAlign: "center",
          fontFamily: "var(--font-body)",
          fontSize: 16,
          fontWeight: 600,
          color: PF_FG,
          letterSpacing: "0.005em",
          lineHeight: 1.2,
        }}
      >
        {title}
      </h1>
      <span aria-hidden="true" />
    </div>
  );
}

function PageShell({ title, onBack, children }) {
  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        display: "flex",
        flexDirection: "column",
        background: PF_BG,
      }}
    >
      <PFHeader title={title} onBack={onBack} />
      <div
        style={{
          flex: 1,
          minHeight: 0,
          overflow: "auto",
          padding: "4px 0 32px",
          display: "flex",
          flexDirection: "column",
        }}
      >
        {children}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────
// Inline icons — kept tiny and consistent (24px stroke, 1.6 weight)
// We don't reuse RadioIcon here because the section icons are distinct
// from the dashboard's categorical iconography.
// ────────────────────────────────────────────────────────────────────
function PFIcon({ name }) {
  const props = {
    width: 22,
    height: 22,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke: "currentColor",
    strokeWidth: 1.6,
    strokeLinecap: "round",
    strokeLinejoin: "round",
  };
  switch (name) {
    case "star":
      return (
        <svg {...props}>
          <path d="M12 3l2.7 5.7 6.3.9-4.6 4.4 1.1 6.3L12 17.4 6.5 20.3l1.1-6.3L3 9.6l6.3-.9L12 3z" />
        </svg>
      );
    case "user":
      return (
        <svg {...props}>
          <circle cx="12" cy="8" r="4" />
          <path d="M4 21c0-4 4-7 8-7s8 3 8 7" />
        </svg>
      );
    case "bell":
      return (
        <svg {...props}>
          <path d="M6 9a6 6 0 1 1 12 0c0 5 2 6 2 6H4s2-1 2-6z" />
          <path d="M10 19a2 2 0 0 0 4 0" />
        </svg>
      );
    case "shield":
      return (
        <svg {...props}>
          <path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6l8-3z" />
          <path d="M9 12l2 2 4-4" />
        </svg>
      );
    case "help":
      return (
        <svg {...props}>
          <circle cx="12" cy="12" r="9" />
          <path d="M9.5 9a2.5 2.5 0 1 1 3.5 2.3c-.8.4-1 1-1 1.7" />
          <circle cx="12" cy="17" r="0.5" fill="currentColor" stroke="none" />
        </svg>
      );
    case "doc":
      return (
        <svg {...props}>
          <path d="M14 3H6a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8l-5-5z" />
          <path d="M14 3v5h5" />
          <path d="M8 13h8M8 17h6" />
        </svg>
      );
    case "trash":
      return (
        <svg {...props}>
          <path d="M4 7h16" />
          <path d="M9 7V4h6v3" />
          <path d="M6 7l1 13a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1l1-13" />
          <path d="M10 11v7M14 11v7" />
        </svg>
      );
    case "external":
      return (
        <svg {...props}>
          <path d="M14 4h6v6" />
          <path d="M20 4l-9 9" />
          <path d="M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5" />
        </svg>
      );
    case "logout":
      return (
        <svg {...props}>
          <path d="M9 4H5a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h4" />
          <path d="M16 17l5-5-5-5" />
          <path d="M21 12H9" />
        </svg>
      );
    default:
      return null;
  }
}

// ────────────────────────────────────────────────────────────────────
// Identity hero card — used in the main /perfil view
// ────────────────────────────────────────────────────────────────────
function IdentityCard({ user, profileKey, onEdit }) {
  const chip = PROFILE_CHIP[profileKey] || PROFILE_CHIP.totalero;
  return (
    <PFCard style={{ margin: "12px 16px 0", padding: "18px 18px 16px" }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
        <PFAvatar
          initials={user.initials || "—"}
          size={56}
          fontSize={20}
          bg={chip.bg}
        />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div
            style={{
              display: "flex",
              alignItems: "flex-start",
              gap: 8,
              justifyContent: "space-between",
            }}
          >
            <div style={{ flex: 1, minWidth: 0 }}>
              <div
                style={{
                  fontFamily: "var(--font-body)",
                  fontSize: 16,
                  fontWeight: 600,
                  color: PF_FG,
                  letterSpacing: "0.005em",
                  lineHeight: 1.25,
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}
              >
                {user.name}
              </div>
              <div
                style={{
                  marginTop: 2,
                  fontFamily: "var(--font-body)",
                  fontSize: 12.5,
                  fontWeight: 400,
                  color: PF_FG_MUTED,
                  letterSpacing: "0.005em",
                  lineHeight: 1.35,
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}
              >
                {user.email}
              </div>
            </div>
            <button
              type="button"
              onClick={onEdit}
              style={{
                background: "transparent",
                border: "none",
                color: PF_BRAND,
                fontFamily: "var(--font-body)",
                fontSize: 12.5,
                fontWeight: 600,
                letterSpacing: "0.01em",
                cursor: "pointer",
                padding: 0,
                whiteSpace: "nowrap",
                flexShrink: 0,
                lineHeight: 1.2,
              }}
            >
              Editar
            </button>
          </div>
          <div style={{ marginTop: 10 }}>
            <span
              style={{
                display: "inline-block",
                padding: "5px 11px",
                borderRadius: 12,
                background: chip.bg,
                color: "#fff",
                fontFamily: "var(--font-body)",
                fontSize: 11,
                fontWeight: 600,
                letterSpacing: "0.04em",
                lineHeight: 1.2,
              }}
            >
              {chip.label}
            </span>
          </div>
        </div>
      </div>

      <div
        style={{
          marginTop: 14,
          paddingTop: 12,
          borderTop: `1px solid ${PF_LINE}`,
          fontFamily: "var(--font-body)",
          fontSize: 12.5,
          fontWeight: 400,
          color: PF_FG_MUTED,
          lineHeight: 1.45,
          letterSpacing: "0.005em",
        }}
      >
        Tu perfil se actualiza conforme avanzas. Cada estado de cuenta nuevo refina tu radiografía.
      </div>
    </PFCard>
  );
}

// ────────────────────────────────────────────────────────────────────
// Logout confirmation modal
// ────────────────────────────────────────────────────────────────────
function LogoutModal({ onCancel, onConfirm }) {
  return (
    <div
      role="dialog"
      aria-modal="true"
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 100,
        background: "rgba(20,32,28,0.42)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 24,
        animation: "pf-fade-in 180ms ease-out",
      }}
    >
      <div
        style={{
          width: "100%",
          maxWidth: 320,
          background: "#fff",
          borderRadius: 18,
          padding: "22px 22px 16px",
          boxShadow: "0 14px 40px rgba(20,32,28,0.30)",
          animation: "pf-pop-in 200ms ease-out",
        }}
      >
        <div
          style={{
            fontFamily: "var(--font-body)",
            fontSize: 17,
            fontWeight: 600,
            color: PF_FG,
            textAlign: "center",
            letterSpacing: "0.005em",
          }}
        >
          ¿Cerrar sesión?
        </div>
        <div
          style={{
            marginTop: 6,
            fontFamily: "var(--font-body)",
            fontSize: 13,
            fontWeight: 400,
            color: PF_FG_MUTED,
            textAlign: "center",
            lineHeight: 1.45,
            letterSpacing: "0.005em",
          }}
        >
          Tendrás que volver a iniciar sesión la próxima vez.
        </div>
        <div
          style={{
            marginTop: 18,
            display: "flex",
            flexDirection: "column",
            gap: 8,
          }}
        >
          <button
            type="button"
            onClick={onConfirm}
            style={{
              width: "100%",
              height: 46,
              borderRadius: 12,
              background: PF_DANGER,
              color: "#fff",
              border: "none",
              fontFamily: "var(--font-body)",
              fontSize: 14,
              fontWeight: 600,
              letterSpacing: "0.01em",
              cursor: "pointer",
            }}
          >
            Sí, cerrar
          </button>
          <button
            type="button"
            onClick={onCancel}
            style={{
              width: "100%",
              height: 46,
              borderRadius: 12,
              background: "transparent",
              color: PF_FG_MUTED,
              border: "none",
              fontFamily: "var(--font-body)",
              fontSize: 14,
              fontWeight: 500,
              letterSpacing: "0.005em",
              cursor: "pointer",
            }}
          >
            Cancelar
          </button>
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────
// MAIN PROFILE VIEW
// ────────────────────────────────────────────────────────────────────
function MainProfileView({ user, profileKey, tier, notifsOn, onNav, onLogout }) {
  return (
    <div data-screen-label="perfil-main" style={{ display: "flex", flexDirection: "column" }}>
      <IdentityCard user={user} profileKey={profileKey} onEdit={() => onNav("info")} />

      {/* SECTIONS LIST */}
      <PFCard style={{ margin: "14px 16px 0", overflow: "hidden" }}>
        <PFRow
          icon={<PFIcon name="star" />}
          title="Mi suscripción"
          subtitle={
            tier.tier === "Free"
              ? "Plan Free · Mejora tu plan"
              : `Plan ${tier.tier} · ${tier.price}`
          }
          subtitleColor={tier.tier === "Free" ? PF_BRAND : PF_FG_MUTED}
          onClick={() => onNav("suscripcion")}
        />
        <PFRow
          icon={<PFIcon name="user" />}
          title="Mi información"
          subtitle="Nombre, email, ciudad"
          onClick={() => onNav("info")}
        />
        <PFRow
          icon={<PFIcon name="bell" />}
          title="Notificaciones"
          subtitle={notifsOn ? "Activadas" : "Desactivadas"}
          onClick={() => onNav("notificaciones")}
        />
        <PFRow
          icon={<PFIcon name="shield" />}
          title="Privacidad y seguridad"
          subtitle="Tus datos están protegidos"
          onClick={() => onNav("privacidad")}
        />
        <PFRow
          icon={<PFIcon name="help" />}
          title="Centro de ayuda"
          subtitle="Preguntas frecuentes y soporte"
          onClick={() => onNav("ayuda")}
          last
        />
      </PFCard>

      {/* LOGOUT */}
      <div style={{ margin: "20px 16px 0" }}>
        <LogoutButton onClick={onLogout} />
      </div>

      {/* VERSION FOOTER */}
      <div
        style={{
          marginTop: 20,
          marginBottom: 8,
          textAlign: "center",
          fontFamily: "var(--font-mono)",
          fontSize: 10.5,
          fontWeight: 400,
          color: PF_FG_SOFT,
          letterSpacing: "0.06em",
          lineHeight: 1.5,
        }}
      >
        yomee.ai · v1.0.0 · Hecho con 🦔 en México
      </div>
    </div>
  );
}

function LogoutButton({ onClick }) {
  const [pressed, setPressed] = useStatePF(false);
  return (
    <button
      type="button"
      onClick={onClick}
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
      onMouseLeave={() => setPressed(false)}
      onTouchStart={() => setPressed(true)}
      onTouchEnd={() => setPressed(false)}
      style={{
        width: "100%",
        height: 56,
        borderRadius: 16,
        background: pressed ? "rgba(51,51,51,0.04)" : "transparent",
        color: PF_DANGER,
        border: "1.5px solid var(--yo-ink)",
        padding: "0 20px",
        fontFamily: "var(--font-mono)",
        fontSize: 13,
        fontWeight: 700,
        letterSpacing: "0.14em",
        cursor: "pointer",
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        gap: 10,
        transition: "background 160ms ease-out",
        whiteSpace: "nowrap",
      }}
    >
      <PFIcon name="logout" />
      <span style={{ whiteSpace: "nowrap" }}>CERRAR SESIÓN</span>
    </button>
  );
}

// ────────────────────────────────────────────────────────────────────
// SUB-VIEW: Mi suscripción (RF-036)
// ────────────────────────────────────────────────────────────────────
const TIER_BENEFITS = {
  Free: [
    "1 estado de cuenta al mes",
    "Radiografía básica",
    "Detección de oportunidades",
  ],
  Plus: [
    "Hasta 5 estados de cuenta al mes",
    "Radiografía completa multibanco",
    "Recomendaciones personalizadas",
    "Recordatorios de pago",
  ],
  Pro: [
    "Estados de cuenta ilimitados",
    "Plan de consolidación con Pocopin",
    "Análisis de patrones avanzados",
    "Soporte prioritario",
  ],
};

const NEXT_TIER = { Free: "Plus", Plus: "Pro", Pro: null };
const TIER_PRICE = { Free: "Gratis", Plus: "$99 MXN/mes", Pro: "$199 MXN/mes" };

function SuscripcionView({ tier, onBack }) {
  const next = NEXT_TIER[tier.tier];
  const benefits = TIER_BENEFITS[tier.tier] || [];
  const nextBenefits = next ? TIER_BENEFITS[next] || [] : [];
  return (
    <PageShell title="Mi suscripción" onBack={onBack}>
      {/* Current tier card */}
      <PFCard style={{ margin: "12px 16px 0", padding: "18px 18px 16px" }}>
        <div
          style={{
            fontFamily: "var(--font-mono)",
            fontSize: 10,
            fontWeight: 700,
            letterSpacing: "0.10em",
            textTransform: "uppercase",
            color: PF_FG_SOFT,
          }}
        >
          Tu plan actual
        </div>
        <div
          style={{
            marginTop: 6,
            display: "flex",
            alignItems: "baseline",
            gap: 8,
          }}
        >
          <span
            style={{
              fontFamily: "var(--font-mono)",
              fontSize: 28,
              fontWeight: 500,
              color: PF_FG,
              letterSpacing: "-0.01em",
            }}
          >
            {tier.tier}
          </span>
          <span
            style={{
              fontFamily: "var(--font-body)",
              fontSize: 13,
              fontWeight: 400,
              color: PF_FG_MUTED,
            }}
          >
            · {TIER_PRICE[tier.tier]}
          </span>
        </div>
        <ul
          style={{
            margin: "14px 0 0",
            padding: 0,
            listStyle: "none",
            display: "flex",
            flexDirection: "column",
            gap: 8,
          }}
        >
          {benefits.map((b, i) => (
            <li
              key={i}
              style={{
                display: "flex",
                gap: 10,
                alignItems: "flex-start",
                fontFamily: "var(--font-body)",
                fontSize: 13,
                fontWeight: 400,
                color: PF_FG,
                letterSpacing: "0.005em",
                lineHeight: 1.45,
              }}
            >
              <span
                aria-hidden="true"
                style={{
                  marginTop: 8,
                  width: 5,
                  height: 5,
                  borderRadius: "50%",
                  background: PF_BRAND,
                  flexShrink: 0,
                }}
              />
              <span style={{ flex: 1, minWidth: 0 }}>{b}</span>
            </li>
          ))}
        </ul>
      </PFCard>

      {/* Upgrade card (ivory) */}
      {next && (
        <PFCard
          style={{
            margin: "12px 16px 0",
            padding: "18px",
            background: PF_IVORY,
            border: "1px solid #efe6cf",
          }}
        >
          <div
            style={{
              fontFamily: "var(--font-mono)",
              fontSize: 10,
              fontWeight: 700,
              letterSpacing: "0.10em",
              textTransform: "uppercase",
              color: "#8a6d1c",
            }}
          >
            Sigue creciendo · {next}
          </div>
          <div
            style={{
              marginTop: 6,
              fontFamily: "var(--font-body)",
              fontSize: 14,
              fontWeight: 600,
              color: PF_FG,
              letterSpacing: "0.005em",
              lineHeight: 1.35,
            }}
          >
            Lo que sumas con {next}
          </div>
          <ul
            style={{
              margin: "10px 0 0",
              padding: 0,
              listStyle: "none",
              display: "flex",
              flexDirection: "column",
              gap: 6,
            }}
          >
            {nextBenefits.map((b, i) => (
              <li
                key={i}
                style={{
                  display: "flex",
                  gap: 10,
                  alignItems: "flex-start",
                  fontFamily: "var(--font-body)",
                  fontSize: 12.5,
                  fontWeight: 400,
                  color: PF_FG,
                  letterSpacing: "0.005em",
                  lineHeight: 1.5,
                }}
              >
                <span
                  aria-hidden="true"
                  style={{
                    color: PF_BRAND,
                    fontWeight: 700,
                    lineHeight: 1.5,
                    fontSize: 13,
                    flexShrink: 0,
                    width: 12,
                    textAlign: "center",
                  }}
                >
                  +
                </span>
                <span style={{ flex: 1, minWidth: 0 }}>{b}</span>
              </li>
            ))}
          </ul>
          <button
            type="button"
            style={{
              marginTop: 16,
              width: "100%",
              height: 46,
              borderRadius: 12,
              background: PF_BRAND,
              color: "#fff",
              border: "none",
              fontFamily: "var(--font-body)",
              fontSize: 14,
              fontWeight: 600,
              letterSpacing: "0.01em",
              cursor: "pointer",
            }}
          >
            Mejorar mi plan
          </button>
          <div
            style={{
              marginTop: 8,
              textAlign: "center",
              fontFamily: "var(--font-body)",
              fontSize: 11,
              color: PF_FG_MUTED,
              letterSpacing: "0.005em",
            }}
          >
            {TIER_PRICE[next]} · Cancela cuando quieras
          </div>
        </PFCard>
      )}

      {/* Payment history */}
      <div
        style={{
          margin: "20px 16px 6px",
          fontFamily: "var(--font-mono)",
          fontSize: 10,
          fontWeight: 700,
          letterSpacing: "0.10em",
          textTransform: "uppercase",
          color: PF_FG_SOFT,
        }}
      >
        Historial de pagos
      </div>
      <PFCard style={{ margin: "0 16px", overflow: "hidden" }}>
        {tier.tier === "Free" ? (
          <div
            style={{
              padding: "22px 18px",
              textAlign: "center",
              fontFamily: "var(--font-body)",
              fontSize: 13,
              color: PF_FG_MUTED,
              letterSpacing: "0.005em",
              lineHeight: 1.5,
            }}
          >
            Aún no tienes pagos. Tu plan {tier.tier} no tiene cargo.
          </div>
        ) : (
          [
            { date: "01 Oct 2025", amount: tier.price },
            { date: "01 Sep 2025", amount: tier.price },
            { date: "01 Ago 2025", amount: tier.price },
          ].map((row, i, arr) => (
            <div
              key={i}
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                padding: "14px 16px",
                borderBottom: i === arr.length - 1 ? "none" : `1px solid ${PF_LINE}`,
              }}
            >
              <span
                style={{
                  fontFamily: "var(--font-body)",
                  fontSize: 13,
                  color: PF_FG,
                  letterSpacing: "0.005em",
                }}
              >
                {row.date}
              </span>
              <span
                style={{
                  fontFamily: "var(--font-mono)",
                  fontSize: 13,
                  fontWeight: 500,
                  color: PF_FG,
                  letterSpacing: "0.005em",
                }}
              >
                {row.amount}
              </span>
            </div>
          ))
        )}
      </PFCard>
    </PageShell>
  );
}

// ────────────────────────────────────────────────────────────────────
// SUB-VIEW: Mi información (RF-033)
// ────────────────────────────────────────────────────────────────────
function InfoView({ user, onBack }) {
  const [name, setName] = useStatePF(user.name || "");
  const [city, setCity] = useStatePF("CDMX");
  const [dob, setDob] = useStatePF("12 / 03 / 1992");

  return (
    <PageShell title="Mi información" onBack={onBack}>
      <PFCard style={{ margin: "12px 16px 0", padding: 4, overflow: "hidden" }}>
        <Field label="Nombre completo" value={name} onChange={setName} />
        <Field label="Email" value={user.email || ""} readOnly />
        <Field label="Ciudad" value={city} onChange={setCity} />
        <Field label="Fecha de nacimiento" value={dob} onChange={setDob} last />
      </PFCard>

      <div style={{ margin: "20px 16px 0" }}>
        <button
          type="button"
          style={{
            width: "100%",
            height: 48,
            borderRadius: 12,
            background: PF_BRAND,
            color: "#fff",
            border: "none",
            fontFamily: "var(--font-body)",
            fontSize: 14,
            fontWeight: 600,
            letterSpacing: "0.01em",
            cursor: "pointer",
          }}
        >
          Guardar cambios
        </button>
      </div>
    </PageShell>
  );
}

function Field({ label, value, onChange, readOnly, last }) {
  return (
    <div
      style={{
        padding: "12px 14px",
        borderBottom: last ? "none" : `1px solid ${PF_LINE}`,
      }}
    >
      <div
        style={{
          fontFamily: "var(--font-mono)",
          fontSize: 10,
          fontWeight: 700,
          letterSpacing: "0.10em",
          textTransform: "uppercase",
          color: PF_FG_SOFT,
        }}
      >
        {label}
      </div>
      <input
        type="text"
        value={value}
        readOnly={readOnly}
        onChange={(e) => onChange && onChange(e.target.value)}
        style={{
          marginTop: 4,
          width: "100%",
          background: "transparent",
          border: "none",
          padding: 0,
          fontFamily: "var(--font-body)",
          fontSize: 15,
          fontWeight: 400,
          color: readOnly ? PF_FG_MUTED : PF_FG,
          letterSpacing: "0.005em",
          outline: "none",
        }}
      />
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────
// SUB-VIEW: Notificaciones (RF-034)
// ────────────────────────────────────────────────────────────────────
const NOTIF_OPTIONS = [
  {
    key: "carga",
    title: "Recordatorio de carga mensual",
    desc: "Avisos para subir tu estado de cuenta cada mes.",
    def: true,
  },
  {
    key: "oportunidades",
    title: "Oportunidades de mercado",
    desc: "Cuando detectamos algo que puede ayudarte a ahorrar.",
    def: true,
  },
  {
    key: "novedades",
    title: "Novedades de yomee",
    desc: "Nuevas funciones y mejoras en la app.",
    def: false,
  },
  {
    key: "pagos",
    title: "Recordatorios de pago próximo",
    desc: "Antes de la fecha límite para que no se te olvide.",
    def: true,
  },
];

function NotificacionesView({ values, setValues, onBack }) {
  return (
    <PageShell title="Notificaciones" onBack={onBack}>
      <PFCard style={{ margin: "12px 16px 0", overflow: "hidden" }}>
        {NOTIF_OPTIONS.map((opt, i, arr) => (
          <ToggleRow
            key={opt.key}
            title={opt.title}
            desc={opt.desc}
            value={values[opt.key]}
            onChange={(v) => setValues({ ...values, [opt.key]: v })}
            last={i === arr.length - 1}
          />
        ))}
      </PFCard>
      <div
        style={{
          margin: "16px 20px 0",
          fontFamily: "var(--font-body)",
          fontSize: 12,
          color: PF_FG_MUTED,
          letterSpacing: "0.005em",
          lineHeight: 1.5,
        }}
      >
        Puedes cambiar tus preferencias en cualquier momento. No usamos tus datos para anuncios.
      </div>
    </PageShell>
  );
}

function ToggleRow({ title, desc, value, onChange, last }) {
  return (
    <div
      style={{
        display: "flex",
        alignItems: "flex-start",
        gap: 12,
        padding: "14px 16px",
        borderBottom: last ? "none" : `1px solid ${PF_LINE}`,
      }}
    >
      <div style={{ flex: 1, minWidth: 0 }}>
        <div
          style={{
            fontFamily: "var(--font-body)",
            fontSize: 14,
            fontWeight: 500,
            color: PF_FG,
            letterSpacing: "0.005em",
            lineHeight: 1.3,
          }}
        >
          {title}
        </div>
        <div
          style={{
            marginTop: 3,
            fontFamily: "var(--font-body)",
            fontSize: 12,
            fontWeight: 400,
            color: PF_FG_MUTED,
            letterSpacing: "0.005em",
            lineHeight: 1.45,
          }}
        >
          {desc}
        </div>
      </div>
      <button
        type="button"
        role="switch"
        aria-checked={value}
        onClick={() => onChange(!value)}
        style={{
          width: 44,
          height: 26,
          borderRadius: 999,
          background: value ? PF_BRAND : "#d4d4d4",
          border: "none",
          padding: 2,
          cursor: "pointer",
          flexShrink: 0,
          marginTop: 2,
          transition: "background 160ms ease-out",
          position: "relative",
        }}
      >
        <span
          style={{
            position: "absolute",
            top: 2,
            left: value ? 20 : 2,
            width: 22,
            height: 22,
            borderRadius: "50%",
            background: "#fff",
            boxShadow: "0 1px 3px rgba(0,0,0,0.2)",
            transition: "left 160ms ease-out",
          }}
        />
      </button>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────
// SUB-VIEW: Privacidad y seguridad (RF-035)
// ────────────────────────────────────────────────────────────────────
function PrivacidadView({ onBack, onOpenLegal, onDeleteAccount }) {
  return (
    <PageShell title="Privacidad y seguridad" onBack={onBack}>
      {/* Ivory banner */}
      <div
        style={{
          margin: "12px 16px 0",
          padding: 16,
          borderRadius: 12,
          background: PF_IVORY,
          border: "1px solid #efe6cf",
          display: "flex",
          gap: 12,
          alignItems: "flex-start",
        }}
      >
        <span
          aria-hidden="true"
          style={{
            width: 28,
            height: 28,
            borderRadius: "50%",
            background: "#efe6cf",
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            color: "#8a6d1c",
            flexShrink: 0,
          }}
        >
          <PFIcon name="shield" />
        </span>
        <div
          style={{
            flex: 1,
            minWidth: 0,
            fontFamily: "var(--font-body)",
            fontSize: 13,
            fontWeight: 400,
            color: "#5a4a18",
            lineHeight: 1.5,
            letterSpacing: "0.005em",
          }}
        >
          Tus estados de cuenta originales se eliminan en cuanto procesamos los datos
          (NIST 800-88). Solo guardamos los números, nunca el documento.
        </div>
      </div>

      {/* 3 rows: Términos, Aviso de privacidad, Eliminar cuenta */}
      <PFCard style={{ margin: "14px 16px 0", overflow: "hidden" }}>
        <PFRow
          icon={<PFIcon name="doc" />}
          title="Términos y condiciones"
          onClick={() => onOpenLegal("terms")}
        />
        <PFRow
          icon={<PFIcon name="shield" />}
          title="Aviso de privacidad"
          onClick={() => onOpenLegal("privacy")}
        />
        <PFRow
          icon={<PFIcon name="trash" />}
          title="Eliminar cuenta"
          danger
          onClick={onDeleteAccount}
          last
        />
      </PFCard>
    </PageShell>
  );
}

// ────────────────────────────────────────────────────────────────────
// SUB-VIEW: Términos y aviso de privacidad (RF-037)
// ────────────────────────────────────────────────────────────────────
function LegalesView({ onBack }) {
  return (
    <PageShell title="Términos y privacidad" onBack={onBack}>
      <PFCard style={{ margin: "12px 16px 0", overflow: "hidden" }}>
        <PFRow
          icon={<PFIcon name="doc" />}
          title="Términos de uso"
          subtitle="Condiciones del servicio"
          onClick={() => {}}
        />
        <PFRow
          icon={<PFIcon name="doc" />}
          title="Aviso de privacidad LFPDPPP"
          subtitle="Cómo tratamos tus datos personales"
          onClick={() => {}}
        />
        <PFRow
          icon={<PFIcon name="doc" />}
          title="Licencias"
          subtitle="Software de terceros"
          onClick={() => {}}
          last
        />
      </PFCard>
    </PageShell>
  );
}

// ────────────────────────────────────────────────────────────────────
// Generic placeholder sub-view (Centro de ayuda + privacy children)
// ────────────────────────────────────────────────────────────────────
function PlaceholderView({ title, body, onBack }) {
  return (
    <PageShell title={title} onBack={onBack}>
      <PFCard style={{ margin: "12px 16px 0", padding: 22 }}>
        <div
          style={{
            fontFamily: "var(--font-body)",
            fontSize: 14,
            fontWeight: 400,
            color: PF_FG,
            lineHeight: 1.55,
            letterSpacing: "0.005em",
          }}
        >
          {body}
        </div>
      </PFCard>
    </PageShell>
  );
}

// ────────────────────────────────────────────────────────────────────
// Top-level ProfileScreen — owns the in-section route + logout modal
// ────────────────────────────────────────────────────────────────────
function ProfileScreen({ onBack, onLoggedOut }) {
  // Active persona drives identity + chip color + tier.
  const yomeeUser = (window.useYomeeUser && window.useYomeeUser()) || {};
  const personaKey = yomeeUser.personaKey || "ana";
  const profileKey = yomeeUser.profile || "totalero";
  const tier = TIER_BY_PERSONA[personaKey] || TIER_BY_PERSONA.ana;

  // In-section sub-route (lives inside ProfileScreen so the parent route
  // stays "perfil" and the back button on the main view returns to the
  // dashboard, not to a stale sub-view).
  const [sub, setSub] = useStatePF("main");
  // Legal modal opened from Privacidad: "terms" | "privacy" | null.
  // Reuses the same BottomSheetModal + TERMS_BODY / PRIVACY_BODY shipped
  // from Shared.jsx and used by sign-up/sign-in.
  const [legal, setLegal] = useStatePF(null);
  const [showLogout, setShowLogout] = useStatePF(false);

  // Notification toggles — local state, persisted only for the session.
  const [notifs, setNotifs] = useStatePF(() => {
    const init = {};
    NOTIF_OPTIONS.forEach((o) => (init[o.key] = o.def));
    return init;
  });
  const notifsOn = Object.values(notifs).some(Boolean);

  // Keep the inner route consistent if persona switches mid-flow.
  useEffectPF(() => {
    setSub("main");
    setLegal(null);
    setShowLogout(false);
  }, [personaKey]);

  // "Eliminar cuenta" — provisional: opens yomee.ai in a new tab.
  function handleDeleteAccount() {
    window.open("https://www.yomee.ai", "_blank");
  }

  function handleLogoutConfirm() {
    setShowLogout(false);
    if (onLoggedOut) onLoggedOut();
  }

  return (
    <div style={{ position: "absolute", inset: 0 }}>
      <style>{`
        @keyframes pf-fade-in { from { opacity: 0; } to { opacity: 1; } }
        @keyframes pf-pop-in {
          from { opacity: 0; transform: scale(0.96); }
          to   { opacity: 1; transform: scale(1); }
        }
      `}</style>

      {sub === "main" && (
        <PageShell title="Mi perfil" onBack={onBack}>
          <MainProfileView
            user={yomeeUser}
            profileKey={profileKey}
            tier={tier}
            notifsOn={notifsOn}
            onNav={(k) => setSub(k)}
            onLogout={() => setShowLogout(true)}
          />
        </PageShell>
      )}

      {sub === "suscripcion" && (
        <SuscripcionView tier={tier} onBack={() => setSub("main")} />
      )}

      {sub === "info" && (
        <InfoView user={yomeeUser} onBack={() => setSub("main")} />
      )}

      {sub === "notificaciones" && (
        <NotificacionesView
          values={notifs}
          setValues={setNotifs}
          onBack={() => setSub("main")}
        />
      )}

      {sub === "privacidad" && (
        <PrivacidadView
          onBack={() => setSub("main")}
          onOpenLegal={(k) => setLegal(k)}
          onDeleteAccount={handleDeleteAccount}
        />
      )}

      {sub === "ayuda" && (
        <AyudaScreen onBack={() => setSub("main")} />
      )}

      {/* Reused legal modals — same components/copy as sign-up/sign-in. */}
      <BottomSheetModal
        open={legal === "terms"}
        title="Términos y condiciones"
        onClose={() => setLegal(null)}
      >
        {TERMS_BODY}
      </BottomSheetModal>
      <BottomSheetModal
        open={legal === "privacy"}
        title="Aviso de privacidad"
        onClose={() => setLegal(null)}
      >
        {PRIVACY_BODY}
      </BottomSheetModal>

      {showLogout && (
        <LogoutModal
          onCancel={() => setShowLogout(false)}
          onConfirm={handleLogoutConfirm}
        />
      )}
    </div>
  );
}

window.ProfileScreen = ProfileScreen;
