/* global React, I, S */
/* Pamp — Settings layout shared between portals */

const { useState: useSetState } = React;

function SettingsShell({ sections, initial }) {
  const [active, setActive] = useSetState(initial || sections.find(s => !s.link)?.key);
  const visible = sections.find(s => s.key === active);

  return (
    <div className="page-enter">
      <S.PageHead eyebrow="Account" title="Settings" sub="Manage your account, preferences, and security." />

      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 28, alignItems: "flex-start" }}>
        <aside className="card" style={{ padding: 8, position: "sticky", top: 0 }}>
          <nav className="col" style={{ gap: 2 }}>
            {sections.map((s) => {
              if (s.divider) return <div key={s.key || s.label} style={{
                fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.12em",
                textTransform: "uppercase", color: "var(--ink-4)",
                padding: "14px 12px 6px",
              }}>{s.label}</div>;
              const Ic = s.icon;
              const isActive = !s.link && active === s.key;
              return (
                <button key={s.key}
                  className={`nav-item${isActive ? " active" : ""}`}
                  onClick={() => s.link ? window.open(s.link, "_blank") : setActive(s.key)}
                  style={{ width: "100%", justifyContent: "flex-start" }}>
                  <span className="ni-icon"><Ic size={16} /></span>
                  <span className="ni-label">{s.label}</span>
                  {s.link && <span style={{ marginLeft: "auto", color: "var(--ink-4)", display: "inline-flex" }}><I.arrowUR size={12} /></span>}
                </button>
              );
            })}
          </nav>
        </aside>

        <div>
          {visible && visible.render()}
        </div>
      </div>
    </div>
  );
}

function SetCard({ title, sub, children, footer }) {
  return (
    <div className="card" style={{ padding: 28, marginBottom: 20 }}>
      <div style={{ marginBottom: 22 }}>
        <div className="h2" style={{ fontSize: 22 }}>{title}</div>
        {sub && <div className="muted" style={{ fontSize: 13, marginTop: 6 }}>{sub}</div>}
      </div>
      {children}
      {footer && <div style={{
        marginTop: 24, paddingTop: 20, borderTop: "1px solid var(--border)",
        display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 10,
      }}>{footer}</div>}
    </div>
  );
}

function FieldRow({ label, hint, children, full }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: full ? "1fr" : "200px 1fr", gap: 18, alignItems: "flex-start", padding: "14px 0", borderTop: "1px solid var(--border)" }}>
      <div>
        <div style={{ fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>{label}</div>
        {hint && <div className="muted tiny" style={{ marginTop: 4 }}>{hint}</div>}
      </div>
      <div>{children}</div>
    </div>
  );
}

function ToggleBtn({ on, onChange }) {
  return (
    <button onClick={() => onChange?.(!on)} style={{
      width: 40, height: 22, borderRadius: 999,
      background: on ? "var(--accent)" : "var(--surface-3)",
      position: "relative", transition: "background 0.2s",
      border: "1px solid var(--border)",
    }}>
      <span style={{
        position: "absolute", top: 1, left: on ? 19 : 1, width: 18, height: 18, borderRadius: 999,
        background: "white", transition: "left 0.2s", boxShadow: "0 1px 3px rgba(0,0,0,0.20)",
      }} />
    </button>
  );
}

function Toggle({ defaultOn = false }) {
  const [on, setOn] = useSetState(defaultOn);
  return <ToggleBtn on={on} onChange={setOn} />;
}

/* ====================================================================
   PROFILE — shared
   ==================================================================== */
function ProfileSection({ kind = "client", data }) {
  const isVendor = kind === "vendor";
  return (
    <SetCard
      title={isVendor ? "Business profile" : "Profile"}
      sub={isVendor ? "Your business identity as it appears to clients." : "Your public profile and contact details."}
      footer={<>
        <S.Btn variant="ghost" size="sm">Cancel</S.Btn>
        <S.Btn variant="primary" size="sm">Save changes</S.Btn>
      </>}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 18, paddingBottom: 18, borderBottom: "1px solid var(--border)" }}>
        {isVendor ? (
          <div style={{ width: 72, height: 72, borderRadius: 16, background: "var(--accent-soft)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--accent-ink)" }}>
            <I.store size={28} />
          </div>
        ) : (
          <S.Avatar name={data?.name || "Amelia Brooks"} size="xl" />
        )}
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 500 }}>{isVendor ? "Logo & cover" : "Profile photo"}</div>
          <div className="muted tiny" style={{ marginTop: 4 }}>PNG or JPG · max 4 MB · square works best</div>
          <div className="row" style={{ gap: 8, marginTop: 10 }}>
            <S.Btn variant="outline" size="sm" icon={<I.export size={12} />}>Upload</S.Btn>
            <S.Btn variant="ghost" size="sm">Remove</S.Btn>
          </div>
        </div>
      </div>

      {isVendor ? <>
        <FieldRow label="Business name" hint="Visible on your booking page.">
          <S.Input value="Maison Color & Co." onChange={() => { }} />
        </FieldRow>
        <FieldRow label="Tagline">
          <S.Input value="Color specialists, editorial finish" onChange={() => { }} />
        </FieldRow>
        <FieldRow label="Category">
          <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
            {["Hair", "Nails", "Spa", "Massage", "Barber", "Wellness"].map((c, i) => (
              <span key={c} className={i === 0 ? "chip chip-accent" : "chip"} style={{ cursor: "pointer", height: 30 }}>{c}</span>
            ))}
          </div>
        </FieldRow>
        <FieldRow label="Address" hint="Used for maps and directions.">
          <S.Input icon={<I.location size={14} />} value="21 Rue de Saintonge, 75003 Paris" onChange={() => { }} />
        </FieldRow>
        <FieldRow label="Hours" hint="Default opening hours.">
          <div className="muted" style={{ fontSize: 13, padding: "9px 0" }}>Mon–Sat · 9:00 – 19:00 · Sun closed</div>
        </FieldRow>
        <FieldRow label="Public phone">
          <S.Input icon={<I.phone size={14} />} value="+33 1 42 71 88 90" onChange={() => { }} />
        </FieldRow>
        <FieldRow label="About" hint="A short paragraph for your profile.">
          <textarea rows={4} className="input" style={{ height: "auto", padding: "12px 14px", display: "block", width: "100%" }}
            defaultValue="Maison Color & Co. is a Parisian studio specializing in editorial color, balayage, and natural shine. Founded by Léa Marchand in 2019." />
        </FieldRow>
      </> : <>
        <FieldRow label="Full name">
          <div className="row" style={{ gap: 8 }}>
            <S.Input value="Amelia" onChange={() => { }} />
            <S.Input value="Brooks" onChange={() => { }} />
          </div>
        </FieldRow>
        <FieldRow label="Display name" hint="Shown on reviews and to vendors.">
          <S.Input value="Amelia B." onChange={() => { }} />
        </FieldRow>
        <FieldRow label="Phone" hint="For appointment reminders only.">
          <S.Input icon={<I.phone size={14} />} value="+44 7700 900 142" onChange={() => { }} />
        </FieldRow>
        <FieldRow label="Date of birth" hint="So vendors can wish you a happy birthday.">
          <S.Input value="14 March 1994" onChange={() => { }} />
        </FieldRow>
        <FieldRow label="City">
          <S.Input icon={<I.location size={14} />} value="London, UK" onChange={() => { }} />
        </FieldRow>
      </>}
    </SetCard>
  );
}

/* ====================================================================
   CHANGE EMAIL
   ==================================================================== */
function EmailSection({ current = "amelia@hey.com" }) {
  return (
    <SetCard
      title="Change email"
      sub="Update the email address you sign in with and receive receipts at."
      footer={<>
        <S.Btn variant="ghost" size="sm">Cancel</S.Btn>
        <S.Btn variant="primary" size="sm">Send verification link</S.Btn>
      </>}
    >
      <div style={{
        padding: 16, marginBottom: 18,
        background: "var(--accent-soft)", color: "var(--accent-ink)",
        borderRadius: 12, display: "flex", alignItems: "center", gap: 12,
      }}>
        <I.check size={16} />
        <div style={{ flex: 1, fontSize: 13 }}>Current email is verified</div>
        <span className="mono tiny">{current}</span>
      </div>
      <FieldRow label="New email" hint="We’ll send a one-time link to confirm.">
        <S.Input icon={<I.mail size={14} />} placeholder="new@example.com" onChange={() => { }} />
      </FieldRow>
      <FieldRow label="Confirm with password" hint="For your security.">
        <S.Input placeholder="••••••••" type="password" onChange={() => { }} />
      </FieldRow>
    </SetCard>
  );
}

/* ====================================================================
   CHANGE PASSWORD
   ==================================================================== */
function PasswordSection() {
  return (
    <SetCard
      title="Change password"
      sub="Strong, unique passwords keep your account safer."
      footer={<>
        <S.Btn variant="ghost" size="sm">Cancel</S.Btn>
        <S.Btn variant="primary" size="sm">Update password</S.Btn>
      </>}
    >
      <FieldRow label="Current password">
        <S.Input placeholder="••••••••" type="password" onChange={() => { }} />
      </FieldRow>
      <FieldRow label="New password" hint="At least 10 characters with one number.">
        <S.Input placeholder="New password" type="password" onChange={() => { }} />
      </FieldRow>
      <FieldRow label="Confirm new password">
        <S.Input placeholder="Repeat password" type="password" onChange={() => { }} />
      </FieldRow>
      <div style={{
        marginTop: 14, padding: 14, borderRadius: 10,
        background: "var(--surface-2)", border: "1px solid var(--border)",
      }}>
        <div className="row-tight" style={{ fontSize: 13, fontWeight: 500 }}>
          <I.sparkle size={14} color="var(--accent-ink)" />
          Two-factor authentication
        </div>
        <div className="muted tiny" style={{ marginTop: 6, marginBottom: 10 }}>
          Add an extra layer of security with an authenticator app.
        </div>
        <S.Btn variant="outline" size="sm" iconRight={<I.arrowR size={12} />}>Set up 2FA</S.Btn>
      </div>
    </SetCard>
  );
}

/* ====================================================================
   DISCOUNT CODE
   ==================================================================== */
function DiscountSection({ kind = "client" }) {
  return (
    <SetCard
      title="Discount code"
      sub={kind === "vendor"
        ? "Redeem partner credits or promotional codes for your subscription."
        : "Have a code? Apply it to your next booking."}
    >
      <div style={{ display: "flex", gap: 10 }}>
        <S.Input icon={<I.coupon size={14} />} placeholder="Enter code" style={{ flex: 1 }} />
        <S.Btn variant="primary">Apply</S.Btn>
      </div>

      <div style={{ marginTop: 28 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>Active codes</div>
        <div className="col" style={{ gap: 8 }}>
          {[
            { code: "WELCOME10", desc: "10% off your first booking", exp: "Expires Mar 30" },
            { code: "PAMPGOLD", desc: "Gold-tier loyalty perk · 15% off facials", exp: "Always" },
          ].map((c) => (
            <div key={c.code} className="row" style={{
              padding: 14, border: "1px dashed var(--border-strong)", borderRadius: 12, gap: 14,
            }}>
              <div style={{
                width: 44, height: 44, borderRadius: 10, background: "var(--accent-soft)",
                color: "var(--accent-ink)", display: "flex", alignItems: "center", justifyContent: "center",
              }}><I.coupon size={18} /></div>
              <div style={{ flex: 1 }}>
                <div className="mono" style={{ fontSize: 14, fontWeight: 600 }}>{c.code}</div>
                <div className="muted tiny" style={{ marginTop: 2 }}>{c.desc}</div>
              </div>
              <div className="muted tiny">{c.exp}</div>
              <S.Btn variant="ghost" size="sm">Remove</S.Btn>
            </div>
          ))}
        </div>
      </div>
    </SetCard>
  );
}

/* ====================================================================
   INVITE FRIENDS
   ==================================================================== */
function InviteSection({ kind = "client" }) {
  return (
    <SetCard
      title="Invite friends"
      sub={kind === "vendor"
        ? "Refer another studio. They get a month free, you get $50 in credit."
        : "Refer a friend. They get $15 off their first booking, you get $15 in credit."}
    >
      {/* hero stat */}
      <div style={{
        padding: 24, borderRadius: 16, marginBottom: 22,
        background: "var(--ink)", color: "var(--surface)", position: "relative", overflow: "hidden",
      }}>
        <div style={{
          position: "absolute", inset: 0, opacity: 0.6,
          background: "radial-gradient(circle at 90% 20%, var(--accent) 0%, transparent 55%)",
        }} />
        <div style={{ position: "relative" }}>
          <div className="eyebrow" style={{ color: "var(--accent)" }}>You’ve earned</div>
          <div className="display" style={{ fontSize: 48, lineHeight: 1, marginTop: 10, color: "var(--surface)" }}>
            $45 <span style={{ fontSize: 16, opacity: 0.5 }}>in credit</span>
          </div>
          <div className="muted tiny" style={{ color: "oklch(85% 0.02 145)", marginTop: 6 }}>3 friends joined · 2 booked</div>
        </div>
      </div>

      {/* share link */}
      <div style={{ marginBottom: 18 }}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>Your invite link</div>
        <div className="row" style={{ gap: 8 }}>
          <S.Input value="pamp.app/i/amelia-7k2" style={{ flex: 1 }} />
          <S.Btn variant="outline" icon={<I.export size={12} />}>Copy</S.Btn>
          <S.Btn variant="primary" icon={<I.mail size={12} />}>Email</S.Btn>
        </div>
      </div>

      {/* by email */}
      <div>
        <div className="eyebrow" style={{ marginBottom: 8 }}>Or send directly</div>
        <div className="row" style={{ gap: 8 }}>
          <S.Input icon={<I.mail size={14} />} placeholder="friend@example.com" style={{ flex: 1 }} />
          <S.Btn variant="primary">Send invite</S.Btn>
        </div>
      </div>

      {/* recent */}
      <div style={{ marginTop: 28 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>Recent invites</div>
        <div className="col" style={{ gap: 8 }}>
          {[
            { e: "mia@hey.com", s: "Booked", st: "pos", date: "Jan 14" },
            { e: "alex@gmail.com", s: "Joined", st: "info", date: "Jan 9" },
            { e: "sarah@me.com", s: "Pending", st: "warn", date: "Jan 4" },
          ].map((r) => (
            <div key={r.e} className="row between" style={{ padding: "10px 14px", border: "1px solid var(--border)", borderRadius: 10 }}>
              <span style={{ fontSize: 13 }}>{r.e}</span>
              <span className="row-tight"><S.Chip tone={r.st}>{r.s}</S.Chip><span className="muted tiny">{r.date}</span></span>
            </div>
          ))}
        </div>
      </div>
    </SetCard>
  );
}

/* ====================================================================
   NOTIFICATIONS
   ==================================================================== */
function NotificationsSection({ kind = "client" }) {
  const channels = ["Email", "Push", "SMS"];
  const groups = kind === "vendor" ? [
    { label: "Bookings", items: ["New bookings", "Cancellations & no-shows", "Booking reminders to clients", "Reschedule requests"] },
    { label: "Money", items: ["Payouts sent", "Failed charges", "Subscription receipts"] },
    { label: "Growth", items: ["Reviews left for you", "Smart promo suggestions", "Weekly performance summary"] },
    { label: "Platform", items: ["Product updates", "Tips & inspiration"] },
  ] : [
    { label: "Bookings", items: ["Booking confirmed", "Reminders (24h before)", "Last-minute changes", "Review requests"] },
    { label: "Wallet & perks", items: ["Receipts", "Refunds", "Loyalty points & rewards"] },
    { label: "Recommendations", items: ["New vendors near me", "Weekly inspiration"] },
    { label: "Platform", items: ["Product updates", "Promotions"] },
  ];

  return (
    <SetCard
      title="Notifications"
      sub="Choose how you’d like to hear from Pamp. We never share your contact details."
    >
      <div style={{ display: "grid", gridTemplateColumns: "1fr 60px 60px 60px", gap: 12, padding: "10px 0", borderBottom: "1px solid var(--border)", alignItems: "center" }}>
        <div className="eyebrow">Type</div>
        {channels.map((c) => (
          <div key={c} className="eyebrow" style={{ textAlign: "center" }}>{c}</div>
        ))}
      </div>

      {groups.map((g) => (
        <div key={g.label}>
          <div style={{
            padding: "16px 0 8px", fontSize: 13, fontWeight: 500, color: "var(--ink-2)",
          }}>{g.label}</div>
          {g.items.map((it, i) => (
            <div key={it} style={{
              display: "grid", gridTemplateColumns: "1fr 60px 60px 60px", gap: 12,
              padding: "12px 0", alignItems: "center",
              borderTop: "1px solid var(--border)",
            }}>
              <div style={{ fontSize: 13 }}>{it}</div>
              {channels.map((c, ci) => (
                <div key={c} style={{ display: "flex", justifyContent: "center" }}>
                  <Toggle defaultOn={ci === 0 || (ci === 1 && i < 2)} />
                </div>
              ))}
            </div>
          ))}
        </div>
      ))}

      <div style={{ marginTop: 22, padding: 14, borderRadius: 10, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
        <div className="row between">
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>Pause all notifications</div>
            <div className="muted tiny" style={{ marginTop: 4 }}>Mute for 24 hours · vacation mode</div>
          </div>
          <Toggle />
        </div>
      </div>
    </SetCard>
  );
}

window.SettingsShell = SettingsShell;
window.ProfileSection = ProfileSection;
window.EmailSection = EmailSection;
window.PasswordSection = PasswordSection;
window.DiscountSection = DiscountSection;
window.InviteSection = InviteSection;
window.NotificationsSection = NotificationsSection;
window.SetCard = SetCard;
window.FieldRow = FieldRow;
window.SetToggle = Toggle;

/* ====================================================================
   DANGER ZONE
   ==================================================================== */
function DangerSection({ kind = "client", openConfirm }) {
  const items = kind === "vendor" ? [
    { key: "export", title: "Export all business data", body: "Download every booking, client, transaction, and payout as a single archive. Takes up to 24 hours.", cta: "Request export", icon: <I.download />, tone: "normal" },
    { key: "transfer", title: "Transfer business ownership", body: "Move this account to another verified Pamp user. Once transferred, you’ll lose admin access.", cta: "Start transfer", icon: <I.users />, tone: "normal" },
    { key: "pause", title: "Pause new bookings", body: "Stops accepting bookings without taking down your profile. Existing appointments stay intact.", cta: "Pause my studio", icon: <I.clock />, tone: "warning" },
    { key: "deactivate", title: "Deactivate account", body: "Remove your profile from Discover and hide all listings. Reactivate anytime in the next 90 days.", cta: "Deactivate", icon: <I.x />, tone: "warning" },
    { key: "delete", title: "Delete account permanently", body: "All bookings, clients, gallery, and transaction history are erased after 30 days. Cannot be undone.", cta: "Delete account", icon: <I.x />, tone: "danger" },
  ] : [
    { key: "export", title: "Download my data", body: "We’ll email you a copy of your bookings, wallet history, and preferences within 24 hours.", cta: "Request my data", icon: <I.download />, tone: "normal" },
    { key: "pause", title: "Pause my account", body: "Hide your profile and stop receiving any communication. Coming back is one click.", cta: "Pause account", icon: <I.clock />, tone: "warning" },
    { key: "delete", title: "Delete account permanently", body: "Booking history is retained for 7 years for tax purposes. Profile and wallet are erased after 30 days.", cta: "Delete account", icon: <I.x />, tone: "danger" },
  ];

  return (
    <div>
      <SetCard
        title="Danger zone"
        sub="Sensitive controls. Each action below is final or near-final — take a breath before proceeding."
      >
        <div className="col" style={{ gap: 14 }}>
          {items.map((it) => {
            const isDanger = it.tone === "danger";
            const isWarn = it.tone === "warning";
            return (
              <div key={it.key} style={{
                padding: 18, borderRadius: 14,
                border: `1px solid ${isDanger ? "var(--neg)" : isWarn ? "var(--warn)" : "var(--border)"}`,
                background: isDanger ? "var(--neg-soft)" : isWarn ? "var(--warn-soft)" : "var(--surface-2)",
                display: "flex", gap: 14, alignItems: "flex-start",
              }}>
                <div style={{
                  width: 38, height: 38, borderRadius: 10, flexShrink: 0,
                  background: isDanger ? "var(--neg)" : isWarn ? "var(--warn)" : "var(--surface-3)",
                  color: isDanger || isWarn ? "white" : "var(--ink-2)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>{React.cloneElement(it.icon, { size: 16 })}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 500 }}>{it.title}</div>
                  <div className="muted" style={{ fontSize: 12.5, marginTop: 4, lineHeight: 1.5 }}>{it.body}</div>
                </div>
                <S.Btn
                  variant="outline"
                  size="sm"
                  onClick={() => openConfirm?.(it)}
                  style={isDanger ? { borderColor: "var(--neg)", color: "var(--neg)" } : {}}
                >{it.cta}</S.Btn>
              </div>
            );
          })}
        </div>
      </SetCard>
    </div>
  );
}

window.DangerSection = DangerSection;
