// ============================================================
//  Mobile — Profile, Edit Profile, Notifications, Settings
//  Loads after extras-v2.jsx + auth-v2.jsx
// ============================================================

// ---- stat tile in profile header ----
function ProfileStat({ value, label }) {
  return (
    <div style={{ flex: 1, textAlign: "center" }}>
      <div style={{ fontFamily: "var(--ff-ui)", fontWeight: 700, fontSize: 24, color: "#fff",
        lineHeight: 1, letterSpacing: "-0.01em" }}>{value}</div>
      <div style={{ fontFamily: "var(--ff-ui)", fontSize: 12, color: "rgba(255,255,255,0.75)",
        marginTop: 5 }}>{label}</div>
    </div>
  );
}

function AccountRow({ icon: Ic, label, detail, badge, onClick, last, destructive }) {
  return (
    <button onClick={onClick} style={{ width: "100%", display: "flex", alignItems: "center", gap: 13,
      padding: "13px 14px", textAlign: "left", background: "none", cursor: "pointer",
      borderTop: "none", borderLeft: "none", borderRight: "none",
      borderBottom: last ? "none" : "1px solid var(--border)" }}>
      <span style={{ width: 34, height: 34, borderRadius: 9, flexShrink: 0,
        background: destructive ? "color-mix(in srgb, var(--red) 10%, transparent)" : "var(--blue-tint)",
        color: destructive ? "var(--red)" : "var(--blue)",
        display: "grid", placeItems: "center" }}><Ic size={18} /></span>
      <span style={{ flex: 1, fontFamily: "var(--ff-ui)", fontSize: 15, fontWeight: 500,
        color: destructive ? "var(--red)" : "var(--text)" }}>{label}</span>
      {badge != null && badge > 0 && (
        <span style={{ minWidth: 20, height: 20, padding: "0 6px", borderRadius: 99,
          background: "var(--red)", color: "#fff", fontFamily: "var(--ff-ui)", fontSize: 11,
          fontWeight: 700, display: "grid", placeItems: "center" }}>{badge}</span>
      )}
      {detail && <span style={{ fontFamily: "var(--ff-ui)", fontSize: 13,
        color: "var(--subtext)" }}>{detail}</span>}
      <span style={{ color: "var(--border-2)" }}><Icons.chevR size={18} /></span>
    </button>
  );
}

// ============================ PROFILE SCREEN ============================
function ProfileScreen({ posts, unread, onOpenNotifications, onOpenNotifSettings,
  onEditProfile, onLogout }) {
  const drafts = posts.filter((p) => p.status === "DRAFT").length;
  const published = posts.filter((p) => p.status === "APPROVED").length;
  return (
    <div style={{ background: "var(--bg-app)", minHeight: "100%" }}>
      {/* blue header */}
      <div style={{ background: "var(--blue)", padding: "4px 16px 20px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <div style={{ width: 64, height: 64, borderRadius: 99, flexShrink: 0,
            background: "#EADDFF", color: "#5B4B8A", display: "grid", placeItems: "center",
            border: "2px solid rgba(255,255,255,0.55)" }}>
            <Icons.user size={34} />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: "var(--ff-ui)", fontWeight: 700, fontSize: 21, color: "#fff",
              letterSpacing: "-0.01em" }}>Arjun Vasudevan</div>
            <div style={{ fontFamily: "var(--ff-ui)", fontSize: 13.5,
              color: "rgba(255,255,255,0.8)" }}>Coimbatore, TN · Citizen reporter</div>
          </div>
          <button onClick={onEditProfile} style={{ color: "#fff", padding: 6, background: "none",
            border: "none", cursor: "pointer" }}>
            <Icons.edit size={19} />
          </button>
        </div>
        <div style={{ display: "flex", marginTop: 16, background: "rgba(255,255,255,0.14)",
          borderRadius: 12, padding: "12px 4px" }}>
          <ProfileStat value="24" label="Reads / day" />
          <div style={{ width: 1, background: "rgba(255,255,255,0.22)" }} />
          <ProfileStat value={published} label="Published" />
          <div style={{ width: 1, background: "rgba(255,255,255,0.22)" }} />
          <ProfileStat value="82%" label="Approval" />
        </div>
      </div>

      {/* tags */}
      <div style={{ padding: "18px 16px 6px" }}>
        <SectionLabel>Tags you post under</SectionLabel>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>
          {["Civic Infrastructure", "Rural Locations", "Cultural Wealth", "Water"].map((t) => (
            <span key={t} style={{ fontFamily: "var(--ff-ui)", fontSize: 12, padding: "4px 11px",
              borderRadius: 8, border: "1px solid var(--border-2)", color: "var(--text-2)",
              background: "var(--bg-card)", whiteSpace: "nowrap" }}>{t}</span>
          ))}
        </div>
      </div>

      {/* account menu */}
      <div style={{ padding: "14px 16px 36px" }}>
        <SectionLabel>Account</SectionLabel>
        <div style={{ background: "var(--bg-card)", borderRadius: 12,
          border: "1px solid var(--border)", overflow: "hidden",
          boxShadow: "var(--shadow-sm)" }}>
          <AccountRow icon={Icons.bell} label="Notifications" badge={unread}
            onClick={onOpenNotifications} />
          <AccountRow icon={Icons.sliders} label="Notification settings"
            onClick={onOpenNotifSettings} />
          <AccountRow icon={Icons.user} label="Edit profile" onClick={onEditProfile} />
          <AccountRow icon={Icons.file} label="Drafts" detail={String(drafts)} />
          <AccountRow icon={Icons.bookmark} label="Saved stories" />
          <AccountRow icon={Icons.help} label="Help & guidelines" />
          <AccountRow icon={Icons.logout} label="Log out" onClick={onLogout}
            last destructive />
        </div>
      </div>
    </div>
  );
}

// ============================ EDIT PROFILE ============================
function EditProfileScreen({ onBack, onSave, showToast }) {
  const [name, setName] = React.useState("Arjun Vasudevan");
  const [bio, setBio] = React.useState("Citizen reporter covering civic infrastructure, water and rural stories across Tamil Nadu.");
  const [loc, setLoc] = React.useState("Coimbatore, TN");
  const [phone, setPhone] = React.useState("+91 98765 43210");
  const [email, setEmail] = React.useState("arjun.v@email.com");

  const handleSave = () => {
    onSave && onSave({ name, bio, loc, phone, email });
    showToast && showToast("Profile updated");
    onBack && onBack();
  };

  const fieldStyle = { display: "block", marginBottom: 16 };
  const labelStyle = { fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 13.5,
    color: "var(--text)", display: "block", marginBottom: 7 };

  return (
    <div style={{ background: "var(--bg-app)", minHeight: "100%" }}>
      {/* header */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px",
        borderBottom: "1px solid var(--border)", background: "var(--bg-card)" }}>
        <button onClick={onBack} style={{ padding: 4, background: "none", border: "none",
          cursor: "pointer", color: "var(--blue)" }}>
          <Icons.chevL size={22} />
        </button>
        <span style={{ fontFamily: "var(--ff-ui)", fontWeight: 700, fontSize: 18,
          color: "var(--text)", flex: 1 }}>Edit profile</span>
        <button onClick={handleSave} style={{ fontFamily: "var(--ff-ui)", fontWeight: 600,
          fontSize: 14, color: "var(--blue)", background: "none", border: "none",
          cursor: "pointer" }}>Save</button>
      </div>

      <div style={{ padding: "20px 16px 36px" }}>
        {/* avatar */}
        <div style={{ display: "flex", justifyContent: "center", marginBottom: 24 }}>
          <div style={{ position: "relative" }}>
            <div style={{ width: 88, height: 88, borderRadius: 99, background: "#EADDFF",
              color: "#5B4B8A", display: "grid", placeItems: "center",
              border: "3px solid var(--border)" }}>
              <Icons.user size={44} />
            </div>
            <button style={{ position: "absolute", bottom: -2, right: -2, width: 32, height: 32,
              borderRadius: 99, background: "var(--blue)", color: "#fff", border: "2px solid var(--bg-app)",
              display: "grid", placeItems: "center", cursor: "pointer" }}>
              <Icons.camera size={16} />
            </button>
          </div>
        </div>

        {/* fields */}
        <label style={fieldStyle}>
          <span style={labelStyle}>Full name</span>
          <div style={{ position: "relative" }}>
            <span style={{ position: "absolute", left: 12, top: 13, color: "var(--subtext)" }}>
              <Icons.user size={18} /></span>
            <input value={name} onChange={(e) => setName(e.target.value)}
              style={{ ...nkInput, paddingLeft: 38 }} />
          </div>
        </label>

        <label style={fieldStyle}>
          <span style={labelStyle}>Bio</span>
          <textarea value={bio} onChange={(e) => setBio(e.target.value)} rows={3}
            style={{ ...nkInput, resize: "none", lineHeight: 1.5 }} />
          <div style={{ fontFamily: "var(--ff-ui)", fontSize: 11.5, color: "var(--subtext)",
            marginTop: 4, textAlign: "right" }}>{bio.length}/200</div>
        </label>

        <label style={fieldStyle}>
          <span style={labelStyle}>Location</span>
          <div style={{ position: "relative" }}>
            <span style={{ position: "absolute", left: 12, top: 13, color: "var(--red)" }}>
              <Icons.pin size={18} /></span>
            <input value={loc} onChange={(e) => setLoc(e.target.value)}
              style={{ ...nkInput, paddingLeft: 38 }} />
          </div>
        </label>

        <label style={fieldStyle}>
          <span style={labelStyle}>Phone number</span>
          <div style={{ position: "relative" }}>
            <span style={{ position: "absolute", left: 12, top: 13, color: "var(--subtext)" }}>
              <Icons.phone size={18} /></span>
            <input value={phone} onChange={(e) => setPhone(e.target.value)}
              style={{ ...nkInput, paddingLeft: 38 }} />
          </div>
        </label>

        <label style={fieldStyle}>
          <span style={labelStyle}>Email</span>
          <div style={{ position: "relative" }}>
            <span style={{ position: "absolute", left: 12, top: 13, color: "var(--subtext)" }}>
              <Icons.mail size={18} /></span>
            <input value={email} onChange={(e) => setEmail(e.target.value)}
              style={{ ...nkInput, paddingLeft: 38 }} />
          </div>
        </label>

        {/* save button */}
        <button onClick={handleSave} style={{ width: "100%", padding: "14px", borderRadius: 11,
          fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 15.5, color: "#fff",
          background: "var(--blue)", border: "none", cursor: "pointer",
          boxShadow: "0 8px 18px rgba(0,68,187,0.28)", marginTop: 4 }}>
          Save changes
        </button>
      </div>
    </div>
  );
}

// ============================ NOTIFICATIONS PANEL (expanded) ============================
const NOTIF_STYLE_V2 = {
  approved:  { icon: Icons.check,      c: "var(--st-approve)" },
  published: { icon: Icons.globe,      c: "var(--st-approve)" },
  changes:   { icon: Icons.edit,       c: "var(--st-review)" },
  review:    { icon: Icons.clock,      c: "var(--st-review)" },
  held:      { icon: Icons.alert,      c: "var(--red)" },
  milestone: { icon: Icons.trophy,     c: "var(--blue)" },
  message:   { icon: Icons.msgCircle,  c: "var(--blue)" },
  deadline:  { icon: Icons.timerReset, c: "var(--st-review)" },
  breaking:  { icon: Icons.zap,        c: "var(--red)" },
  article:   { icon: Icons.newspaper,  c: "var(--blue-mid)" },
};

function NotificationsPanel({ notifs, onClose, onOpenItem }) {
  const sections = [
    { label: "New", items: notifs.filter((n) => n.unread) },
    { label: "Earlier", items: notifs.filter((n) => !n.unread) },
  ].filter((s) => s.items.length > 0);

  return (
    <div onClick={onClose} style={{ position: "absolute", inset: 0, zIndex: 80,
      display: "flex", flexDirection: "column", justifyContent: "flex-start",
      background: "color-mix(in srgb, #0a0f1a 45%, transparent)",
      animation: "nk-fade .18s ease" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: "var(--bg-app)",
        marginTop: 92, borderTopLeftRadius: 22, borderTopRightRadius: 22, flex: 1,
        display: "flex", flexDirection: "column", overflow: "hidden",
        animation: "nk-slideup .26s cubic-bezier(.2,.8,.2,1)" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "16px 18px 12px", borderBottom: "1px solid var(--border)" }}>
          <span style={{ fontFamily: "var(--ff-ui)", fontWeight: 700, fontSize: 18,
            color: "var(--text)" }}>Notifications</span>
          <button onClick={onClose} style={{ color: "var(--subtext)", background: "none",
            border: "none", cursor: "pointer", padding: 4 }}><Icons.x size={20} /></button>
        </div>
        <div style={{ overflow: "auto", flex: 1, padding: "0 0 24px" }}>
          {sections.map((sec) => (
            <div key={sec.label}>
              <div style={{ padding: "12px 18px 6px", fontFamily: "var(--ff-ui)", fontSize: 12,
                fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase",
                color: "var(--subtext)" }}>{sec.label}</div>
              {sec.items.map((n) => {
                const st = NOTIF_STYLE_V2[n.type] || NOTIF_STYLE_V2.review;
                const Ic = st.icon;
                const actionable = n.type === "changes" || n.type === "deadline";
                return (
                  <button key={n.id} onClick={() => onOpenItem(n)} style={{ width: "100%",
                    display: "flex", gap: 12, padding: "13px 18px", textAlign: "left",
                    background: n.unread
                      ? "color-mix(in srgb, var(--blue) 5%, transparent)" : "none",
                    border: "none", borderBottom: "1px solid var(--border)",
                    cursor: "pointer" }}>
                    <span style={{ width: 36, height: 36, borderRadius: 10, flexShrink: 0,
                      color: st.c, background: `color-mix(in srgb, ${st.c} 13%, transparent)`,
                      display: "grid", placeItems: "center" }}><Ic size={18} /></span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontFamily: "var(--ff-ui)", fontSize: 14, lineHeight: 1.4,
                        color: "var(--text)" }}
                        dangerouslySetInnerHTML={{ __html: n.text }} />
                      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 5 }}>
                        <span style={{ fontFamily: "var(--ff-ui)", fontSize: 11.5,
                          color: "var(--subtext)" }}>{n.time}</span>
                        {actionable && (
                          <span style={{ fontFamily: "var(--ff-ui)", fontSize: 11.5,
                            fontWeight: 600, color: "var(--blue)", display: "inline-flex",
                            alignItems: "center", gap: 3 }}>
                            <Icons.edit size={12} /> Tap to edit
                          </span>
                        )}
                      </div>
                    </div>
                    {n.unread && <span style={{ width: 8, height: 8, borderRadius: 99,
                      background: "var(--blue)", flexShrink: 0, marginTop: 6 }} />}
                  </button>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ============================ NOTIFICATION SETTINGS (expanded) ============================
function ToggleRow({ label, sub, value, onChange, last }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 14px",
      borderBottom: last ? "none" : "1px solid var(--border)" }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: "var(--ff-ui)", fontSize: 14.5, fontWeight: 500,
          color: "var(--text)" }}>{label}</div>
        {sub && <div style={{ fontFamily: "var(--ff-ui)", fontSize: 12.5,
          color: "var(--subtext)", marginTop: 3, lineHeight: 1.4 }}>{sub}</div>}
      </div>
      <button onClick={() => onChange(!value)} style={{ flexShrink: 0, width: 46, height: 27,
        borderRadius: 99, padding: 3, border: "none", cursor: "pointer", display: "flex",
        background: value ? "var(--blue)" : "var(--border-2)",
        transition: "background .18s ease" }}>
        <span style={{ width: 21, height: 21, borderRadius: 99, background: "#fff",
          boxShadow: "0 1px 3px rgba(0,0,0,0.3)",
          transform: value ? "translateX(19px)" : "translateX(0)",
          transition: "transform .18s cubic-bezier(.4,0,.2,1)" }} />
      </button>
    </div>
  );
}

function SettingsSheet({ settings, onChange, onClose }) {
  return (
    <div onClick={onClose} style={{ position: "absolute", inset: 0, zIndex: 80,
      display: "flex", flexDirection: "column", justifyContent: "flex-end",
      background: "color-mix(in srgb, #0a0f1a 45%, transparent)",
      animation: "nk-fade .18s ease" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: "var(--bg-app)",
        borderTopLeftRadius: 22, borderTopRightRadius: 22, paddingBottom: 30,
        maxHeight: "82%", overflow: "auto",
        animation: "nk-slideup .26s cubic-bezier(.2,.8,.2,1)" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "16px 18px 12px", position: "sticky", top: 0, zIndex: 1,
          background: "var(--bg-app)" }}>
          <span style={{ fontFamily: "var(--ff-ui)", fontWeight: 700, fontSize: 18,
            color: "var(--text)" }}>Notification settings</span>
          <button onClick={onClose} style={{ color: "var(--subtext)", background: "none",
            border: "none", cursor: "pointer", padding: 4 }}><Icons.x size={20} /></button>
        </div>

        {/* Section 1: Your articles */}
        <div style={{ padding: "0 16px 16px" }}>
          <SectionLabel>Your articles</SectionLabel>
          <div style={{ background: "var(--bg-card)", borderRadius: 14,
            border: "1px solid var(--border)", overflow: "hidden" }}>
            <ToggleRow label="Status changes"
              sub="Notified when an editor approves, holds, or rejects your post."
              value={settings.statusChange} onChange={(v) => onChange("statusChange", v)} />
            <ToggleRow label="Editor messages"
              sub="Replies and change requests from the editorial desk."
              value={settings.editorMsg} onChange={(v) => onChange("editorMsg", v)} />
            <ToggleRow label="Story milestones"
              sub="When a published story passes 1k / 5k / 10k reads."
              value={settings.milestones} onChange={(v) => onChange("milestones", v)} />
            <ToggleRow label="Edit deadlines"
              sub="Reminders when requested changes are due."
              value={settings.deadlines} onChange={(v) => onChange("deadlines", v)} last />
          </div>
        </div>

        {/* Section 2: News & updates */}
        <div style={{ padding: "0 16px 16px" }}>
          <SectionLabel>News &amp; updates</SectionLabel>
          <div style={{ background: "var(--bg-card)", borderRadius: 14,
            border: "1px solid var(--border)", overflow: "hidden" }}>
            <ToggleRow label="Breaking news"
              sub="Urgent stories sent to all reporters."
              value={settings.breaking} onChange={(v) => onChange("breaking", v)} />
            <ToggleRow label="New articles on site"
              sub="Latest stories published on nambikkai.com."
              value={settings.newArticles} onChange={(v) => onChange("newArticles", v)} />
            <ToggleRow label="Editor picks"
              sub="Highlighted stories selected by the editorial team."
              value={settings.editorPicks} onChange={(v) => onChange("editorPicks", v)} last />
          </div>
        </div>

        <div style={{ padding: "0 22px", fontFamily: "var(--ff-ui)", fontSize: 12,
          color: "var(--subtext)", lineHeight: 1.45 }}>
          Push notifications are sent to this device. Manage email alerts on the web.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ProfileScreen, EditProfileScreen, NotificationsPanel, SettingsSheet });
