// Agent Portal — rewards.com.sg

const { useState: useStateA, useEffect: useEffectA } = React;

// ── Agent Profile Preview Card (how clients see this agent) ──
function AgentProfileCard({ profile, compact }) {
  const accent = profile.accentColor || "#84e3f3";
  const meetLabels = {
    meet: { icon:"☕", text:"Meet me to claim", sub:"Low-pressure coffee or tea" },
    whatsapp: { icon:"💬", text:"WhatsApp me to claim", sub:"Quick digital handshake" },
    open: { icon:"🎁", text:"Open gift — no meeting needed", sub:"For existing policyholders" },
    policyholder: { icon:"🔒", text:"Existing clients only", sub:"Exclusive policyholder perk" },
  };
  const rule = meetLabels[profile.meetingRule] || meetLabels.meet;

  return (
    <div style={{
      borderRadius: compact ? 20 : 28,
      overflow:"hidden",
      border:`1.5px solid ${accent}44`,
      background:`linear-gradient(145deg, rgba(11,25,45,0.98), rgba(7,13,24,0.98))`,
      boxShadow: compact ? "none" : `0 24px 60px rgba(0,0,0,0.4), 0 0 0 1px ${accent}22`,
    }}>
      {/* Accent header strip */}
      <div style={{ height:6, background:`linear-gradient(90deg,${accent},${accent}66,transparent)` }} />
      <div style={{ padding: compact ? "16px 18px" : "24px 26px" }}>
        {/* Avatar + name */}
        <div style={{ display:"flex", gap:14, alignItems:"flex-start", marginBottom: compact ? 12 : 18 }}>
          <div style={{
            width: compact ? 48 : 64, height: compact ? 48 : 64, borderRadius: compact ? 14 : 18, flexShrink:0,
            background:`linear-gradient(135deg,${accent}55,rgba(7,14,26,0.9))`,
            display:"grid", placeItems:"center",
            fontFamily:"'Barlow Condensed',sans-serif",
            fontSize: compact ? "1.2rem" : "1.75rem", fontWeight:800, color:"#f1ece7",
            border:`1px solid ${accent}33`,
          }}>{profile.initials || (profile.name||"?").split(" ").map(w=>w[0]).join("").slice(0,2)}</div>
          <div style={{ flex:1 }}>
            <div style={{ fontFamily:"'Barlow Condensed',sans-serif", fontSize: compact ? "1.4rem" : "1.9rem", fontWeight:800, color:"#f1ece7", lineHeight:1 }}>{profile.name || "Your Name"}</div>
            <div style={{ fontSize:"0.78rem", color:"#8b97ab", marginTop:3 }}>{profile.description || "Licensed financial consultant"}</div>
            <div style={{ fontSize:"0.72rem", color:accent, marginTop:2, fontWeight:700 }}>{profile.agency || "Your Agency"}</div>
          </div>
          {!compact && (
            <div style={{ textAlign:"right", fontSize:"0.7rem", color:"#8b97ab" }}>
              <div style={{ fontFamily:"'Barlow Condensed',sans-serif", fontSize:"1.6rem", fontWeight:800, color:"#f1ece7" }}>{profile.clientsClaimed || 0}</div>
              <div>clients</div>
            </div>
          )}
        </div>

        {/* Bio */}
        {profile.bio && (
          <p style={{ margin:"0 0 14px", fontSize:"0.84rem", color:"#c6cedd", lineHeight:1.6, fontStyle:"italic" }}>
            "{profile.bio}"
          </p>
        )}

        {/* Meeting rule */}
        <div style={{
          borderRadius:12, padding:"10px 14px", marginBottom:12,
          background:`${accent}12`, border:`1px solid ${accent}28`,
          display:"flex", gap:10, alignItems:"center",
        }}>
          <span style={{ fontSize:"1.1rem" }}>{rule.icon}</span>
          <div>
            <div style={{ fontWeight:700, fontSize:"0.82rem", color:accent }}>{rule.text}</div>
            <div style={{ fontSize:"0.72rem", color:"#8b97ab" }}>{rule.sub}</div>
          </div>
        </div>

        {/* Specialties */}
        {profile.specialties?.length > 0 && (
          <div style={{ display:"flex", flexWrap:"wrap", gap:6, marginBottom: compact ? 0 : 14 }}>
            {profile.specialties.map((s, i) => (
              <span key={i} style={{ padding:"4px 11px", borderRadius:999, fontSize:"0.7rem", fontWeight:700, background:`${accent}18`, color:accent }}>{s}</span>
            ))}
          </div>
        )}

        {/* CTA */}
        {!compact && (
          <div style={{ display:"flex", gap:8, marginTop:14 }}>
            <button style={{ all:"unset", cursor:"pointer", padding:"9px 18px", borderRadius:999, background:accent, color:"#08111f", fontWeight:800, fontSize:"0.82rem" }}>
              Connect with {profile.name?.split(" ")[0] || "agent"}
            </button>
            <button style={{ all:"unset", cursor:"pointer", padding:"9px 18px", borderRadius:999, border:`1px solid ${accent}44`, color:accent, fontSize:"0.82rem", fontWeight:700 }}>
              💬 WhatsApp
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

function CollabFormatChips({ formats }) {
  if (!formats?.length) return null;
  return (
    <div style={{ display:"flex", flexWrap:"wrap", gap:6, marginTop:12 }}>
      {formats.map((format) => (
        <span key={format} style={{
          padding:"4px 10px",
          borderRadius:999,
          fontSize:"0.7rem",
          fontWeight:700,
          background:"rgba(255,255,255,0.05)",
          color:"#c6cedd",
        }}>
          {format}
        </span>
      ))}
    </div>
  );
}

function CollabViewModeToggle({ viewMode, onChange }) {
  return (
    <div style={{ display:"flex", borderRadius:10, border:"1px solid rgba(255,255,255,0.1)", overflow:"hidden" }}>
      {[["grid","⊞"],["list","≡"],["carousel","◎"]].map(([mode, icon]) => (
        <button key={mode} onClick={() => onChange(mode)}
          style={{
            all:"unset",
            cursor:"pointer",
            padding:"6px 12px",
            fontSize:"0.85rem",
            background: viewMode === mode ? "rgba(132,227,243,0.15)" : "transparent",
            color: viewMode === mode ? "#84e3f3" : "#8b97ab",
            borderRight: mode !== "carousel" ? "1px solid rgba(255,255,255,0.08)" : "none",
            transition:"all 150ms ease",
          }}
        >
          {icon} {mode}
        </button>
      ))}
    </div>
  );
}

function CollabSectionHeader({ title, eyebrow, description, controls }) {
  return (
    <div style={{ display:"flex", gap:12, alignItems:"center", justifyContent:"space-between", flexWrap:"wrap" }}>
      <div style={{ display:"grid", gap:5, maxWidth:"900px" }}>
        {title && (
          <div style={{
            fontFamily:"'Barlow Condensed',sans-serif",
            fontSize:"1.55rem",
            fontWeight:800,
            color:"#f1ece7",
            lineHeight:1,
          }}>
            {title}
          </div>
        )}
        {eyebrow && (
          <div style={{ fontSize:"0.78rem", fontWeight:800, letterSpacing:"0.12em", textTransform:"uppercase", color:"#84e3f3" }}>
            {eyebrow}
          </div>
        )}
        {description && (
          <div style={{ fontSize:"0.8rem", color:"#8b97ab", lineHeight:1.5 }}>
            {description}
          </div>
        )}
      </div>
      {controls || null}
    </div>
  );
}

function CollabProgramBlocks({ programs, color, large }) {
  if (!programs?.length) return null;
  return (
    <div style={{ display:"grid", gap:8, marginTop:12 }}>
      {programs.map((program) => (
        <div key={program.title} style={{
          borderRadius:14,
          padding: large ? "12px 14px" : "10px 12px",
          background:"rgba(255,255,255,0.04)",
          border:`1px solid ${(color || "#84e3f3")}22`,
        }}>
          <div style={{ display:"flex", gap:8, alignItems:"center", flexWrap:"wrap" }}>
            <div style={{
              fontWeight:800,
              fontSize: large ? "0.9rem" : "0.8rem",
              color:"#f1ece7",
            }}>
              {program.title}
            </div>
            {program.price && (
              <span style={{
                padding:"3px 9px",
                borderRadius:999,
                fontSize:"0.68rem",
                fontWeight:800,
                background:`${color || "#84e3f3"}18`,
                color: color || "#84e3f3",
              }}>
                {program.price}
              </span>
            )}
          </div>
          <div style={{
            fontSize: large ? "0.82rem" : "0.78rem",
            color:"#c6cedd",
            lineHeight:1.55,
            marginTop:6,
          }}>
            {program.description}
          </div>
        </div>
      ))}
    </div>
  );
}

function CollabPartnerDetails({ partner, large }) {
  const tone = partner.color || "#84e3f3";
  const subheading = partner.tagline || partner.subtitle;
  return (
    <>
      <div style={{ display:"flex", gap:8, alignItems:"center", flexWrap:"wrap" }}>
        <div style={{
          fontWeight:800,
          fontSize: large ? "1rem" : "0.92rem",
          color:"#f1ece7",
        }}>
          {partner.name}
        </div>
        <span style={{
          padding:"3px 10px",
          borderRadius:999,
          fontSize:"0.68rem",
          fontWeight:800,
          background:`${tone}18`,
          color:tone,
        }}>
          {partner.category}
        </span>
        {partner.featuredLabel && (
          <span style={{
            padding:"3px 10px",
            borderRadius:999,
            fontSize:"0.68rem",
            fontWeight:800,
            background:"rgba(245,158,11,0.14)",
            color:"#fbbf24",
          }}>
            {partner.featuredLabel}
          </span>
        )}
        {partner.badges?.map((badge) => (
          <span key={badge.label} style={{
            padding:"3px 10px",
            borderRadius:999,
            fontSize:"0.68rem",
            fontWeight:800,
            background: badge.background || "rgba(255,255,255,0.1)",
            color: badge.color || "#f1ece7",
          }}>
            {badge.label}
          </span>
        ))}
      </div>
      {subheading && (
        <div style={{
          fontSize: large ? "0.88rem" : "0.78rem",
          color:"#8b97ab",
          marginTop:4,
        }}>
          {subheading}
        </div>
      )}
      {partner.offer && (
        <p style={{
          margin:"10px 0 0",
          fontSize: large ? "0.86rem" : "0.82rem",
          color:"#c6cedd",
          lineHeight:1.6,
        }}>
          {partner.offer}
        </p>
      )}
      <CollabProgramBlocks programs={partner.programs} color={tone} large={large} />
      {partner.notes?.length > 0 && (
        <div style={{ display:"grid", gap:8, marginTop:12 }}>
          {partner.notes.map((note) => (
            <div key={note} style={{
              borderRadius:12,
              padding: large ? "11px 13px" : "10px 12px",
              background:"rgba(255,255,255,0.04)",
              border:`1px solid ${tone}22`,
              fontSize: large ? "0.8rem" : "0.76rem",
              color:"#c6cedd",
              lineHeight:1.55,
            }}>
              {note}
            </div>
          ))}
        </div>
      )}
      {partner.actions?.length > 0 && (
        <div style={{ display:"flex", gap:8, flexWrap:"wrap", marginTop:12 }}>
          {partner.actions.map((action) => (
            <button key={action.label} style={{
              all:"unset",
              cursor:"pointer",
              padding: large ? "9px 18px" : "8px 14px",
              borderRadius:999,
              background: action.kind === "primary" ? "rgba(37,211,102,0.15)" : "transparent",
              border: action.kind === "primary" ? "none" : `1px solid ${tone}4d`,
              color: action.kind === "primary" ? "#25d366" : tone,
              fontWeight:800,
              fontSize: large ? "0.82rem" : "0.76rem",
            }}>
              {action.label}
            </button>
          ))}
        </div>
      )}
      <CollabFormatChips formats={partner.talkFormats} />
    </>
  );
}

function CollabGridView({ partners, accent }) {
  return (
    <div style={{
      display:"grid",
      gridTemplateColumns:"repeat(auto-fit,minmax(260px,1fr))",
      gap:12,
    }}>
      {partners.map((partner) => (
        <div key={partner.id} style={{
          borderRadius:18,
          padding:"16px 18px",
          background: partner.featured
            ? `linear-gradient(145deg,${(partner.color || accent)}1c,rgba(255,255,255,0.05))`
            : "rgba(255,255,255,0.04)",
          border: partner.featured
            ? `1px solid ${(partner.color || accent)}55`
            : "1px solid rgba(255,255,255,0.08)",
          boxShadow: partner.featured ? `0 0 0 1px ${(partner.color || accent)}18` : "none",
        }}>
          <div style={{ display:"flex", gap:12, alignItems:"flex-start" }}>
            <div style={{
              width:48,
              height:48,
              borderRadius:14,
              flexShrink:0,
              background:`linear-gradient(135deg,${(partner.color || accent)}33,rgba(7,14,26,0.96))`,
              display:"grid",
              placeItems:"center",
              fontSize:"1.25rem",
            }}>
              {partner.emoji || "🎤"}
            </div>
            <div style={{ flex:1, minWidth:0 }}>
              <CollabPartnerDetails partner={partner} />
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function CollabListView({ partners, accent }) {
  return (
    <div style={{ display:"grid", gap:10 }}>
      {partners.map((partner) => (
        <div key={partner.id} style={{
          borderRadius:16,
          padding:"16px 18px",
          background: partner.featured
            ? `linear-gradient(145deg,${(partner.color || accent)}18,rgba(255,255,255,0.04))`
            : "rgba(255,255,255,0.04)",
          border: partner.featured
            ? `1px solid ${(partner.color || accent)}55`
            : "1px solid rgba(255,255,255,0.08)",
        }}>
          <div style={{ display:"flex", gap:12, alignItems:"flex-start" }}>
            <div style={{
              width:44,
              height:44,
              borderRadius:12,
              flexShrink:0,
              background:`linear-gradient(135deg,${(partner.color || accent)}33,rgba(7,14,26,0.96))`,
              display:"grid",
              placeItems:"center",
              fontSize:"1.2rem",
            }}>
              {partner.emoji || "🎤"}
            </div>
            <div style={{ flex:1, minWidth:0 }}>
              <CollabPartnerDetails partner={partner} />
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function CollabCarouselView({ partners, accent }) {
  const [idx, setIdx] = useStateA(0);
  useEffectA(() => {
    if (!partners.length) return;
    setIdx((current) => Math.min(current, partners.length - 1));
  }, [partners.length]);

  const partner = partners[idx];
  if (!partner) return null;

  return (
    <div style={{ userSelect:"none" }}>
      <div style={{
        borderRadius:26,
        overflow:"hidden",
        border:`1.5px solid ${partner.color || accent}`,
        background:`linear-gradient(145deg, ${(partner.color || accent)}22 0%, rgba(7,14,26,0.98) 55%)`,
        marginBottom:16,
        padding:"24px 24px 22px",
        boxShadow:`0 24px 60px rgba(0,0,0,0.36), 0 0 0 1px ${(partner.color || accent)}22`,
        transition:"all 240ms ease",
      }}>
        <div style={{ display:"flex", gap:16, alignItems:"flex-start" }}>
          <div style={{
            width:60,
            height:60,
            borderRadius:18,
            flexShrink:0,
            background:`linear-gradient(135deg,${(partner.color || accent)}44,rgba(7,14,26,0.96))`,
            display:"grid",
            placeItems:"center",
            fontSize:"1.7rem",
          }}>
            {partner.emoji || "🎤"}
          </div>
          <div style={{ flex:1, minWidth:0 }}>
            <CollabPartnerDetails partner={partner} large={true} />
          </div>
        </div>
      </div>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"center", gap:12 }}>
        <button
          onClick={() => setIdx((current) => Math.max(0, current - 1))}
          style={{
            all:"unset",
            cursor:"pointer",
            width:36,
            height:36,
            borderRadius:999,
            border:"1px solid rgba(132,227,243,0.2)",
            display:"grid",
            placeItems:"center",
            color:"#84e3f3",
            fontSize:"1rem",
          }}
        >
          ←
        </button>
        {partners.map((item, itemIdx) => (
          <button
            key={item.id}
            onClick={() => setIdx(itemIdx)}
            style={{
              all:"unset",
              cursor:"pointer",
              width: itemIdx === idx ? 20 : 8,
              height:8,
              borderRadius:999,
              background: itemIdx === idx ? (item.color || accent) : "rgba(255,255,255,0.18)",
              transition:"all 200ms ease",
            }}
          />
        ))}
        <button
          onClick={() => setIdx((current) => Math.min(partners.length - 1, current + 1))}
          style={{
            all:"unset",
            cursor:"pointer",
            width:36,
            height:36,
            borderRadius:999,
            border:"1px solid rgba(132,227,243,0.2)",
            display:"grid",
            placeItems:"center",
            color:"#84e3f3",
            fontSize:"1rem",
          }}
        >
          →
        </button>
      </div>
    </div>
  );
}

function CollabCollectionView({ items, accent, viewMode }) {
  if (!items?.length) return null;
  if (viewMode === "grid") return <CollabGridView partners={items} accent={accent} />;
  if (viewMode === "list") return <CollabListView partners={items} accent={accent} />;
  return <CollabCarouselView partners={items} accent={accent} />;
}

// ── ONBOARDING STEPS ───────────────────────────────────────
const ONBOARDING_STEPS = ["Basic info","Agency details","Specialties","Claim rules","Preview & launch"];

function StepIndicator({ current, total }) {
  return (
    <div style={{ display:"flex", alignItems:"center", gap:0, marginBottom:28 }}>
      {Array.from({ length: total }).map((_, i) => (
        <React.Fragment key={i}>
          <div style={{
            width: i === current ? 28 : 22, height: i === current ? 28 : 22,
            borderRadius:999, display:"grid", placeItems:"center",
            background: i < current ? "#84e3f3" : i === current ? "#84e3f3" : "rgba(255,255,255,0.08)",
            color: i <= current ? "#08111f" : "#8b97ab",
            fontWeight:800, fontSize:"0.78rem", flexShrink:0,
            border: i === current ? "2px solid #84e3f3" : "none",
            transition:"all 200ms ease",
          }}>{i < current ? "✓" : i + 1}</div>
          {i < total - 1 && (
            <div style={{ flex:1, height:2, background: i < current ? "#84e3f3" : "rgba(255,255,255,0.08)", minWidth:12, transition:"all 300ms ease" }} />
          )}
        </React.Fragment>
      ))}
    </div>
  );
}

function Field({ label, hint, children }) {
  return (
    <label style={{ display:"grid", gap:6 }}>
      <span style={{ fontWeight:700, fontSize:"0.84rem", color:"#c6cedd" }}>{label}</span>
      {children}
      {hint && <span style={{ fontSize:"0.72rem", color:"#8b97ab" }}>{hint}</span>}
    </label>
  );
}

const inputStyle = {
  borderRadius:12, border:"1px solid rgba(132,227,243,0.2)",
  background:"rgba(255,255,255,0.04)", color:"#f1ece7",
  padding:"11px 14px", fontSize:"0.88rem", width:"100%",
  boxSizing:"border-box",
};

const SPECIALTIES_OPTIONS = [
  "Wealth protection","Legacy planning","Family risk","Health planning",
  "Investment-linked","Term insurance","Whole life","Referral nurturing",
  "Claims readiness","Client appreciation","Team activation","High-net-worth",
];

function AgentOnboarding({ onComplete }) {
  const [step, setStepRaw] = useStateA(0);
  const [profile, setProfile] = useStateA({
    name:"", email:"", mobile:"", whatsapp:"",
    agency:"", repCode:"", teamLeader:"",
    specialties:[], bio:"", meetingRule:"meet",
    accentColor:"#84e3f3", billingPref:"prepaid",
  });

  const set = (key, val) => setProfile(p => ({ ...p, [key]: val }));
  const setStep = n => setStepRaw(Math.max(0, Math.min(ONBOARDING_STEPS.length - 1, n)));

  const toggleSpecialty = s => {
    set("specialties", profile.specialties.includes(s)
      ? profile.specialties.filter(x => x !== s)
      : [...profile.specialties, s]);
  };

  const previewProfile = {
    ...profile,
    initials: profile.name.split(" ").map(w => w[0]).join("").slice(0, 2).toUpperCase() || "??",
    description: profile.bio?.slice(0, 60) || "Licensed financial consultant",
    clientsClaimed: 0,
  };

  return (
    <div style={{ display:"grid", gap:0, height:"100%", overflow:"hidden" }}>
      {/* Progress */}
      <div style={{ padding:"0 0 0" }}>
        <StepIndicator current={step} total={ONBOARDING_STEPS.length} />
        <div style={{ fontFamily:"'Barlow Condensed',sans-serif", fontSize:"1.9rem", fontWeight:800, color:"#f1ece7", marginBottom:4 }}>
          {ONBOARDING_STEPS[step]}
        </div>
        <div style={{ fontSize:"0.8rem", color:"#8b97ab", marginBottom:22 }}>
          Step {step + 1} of {ONBOARDING_STEPS.length}
        </div>
      </div>

      {/* Step content */}
      <div style={{ flex:1, overflowY:"auto" }}>
        {step === 0 && (
          <div style={{ display:"grid", gap:14 }}>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12 }}>
              <Field label="Full name">
                <input style={inputStyle} value={profile.name} onChange={e => set("name", e.target.value)} placeholder="Your legal name" />
              </Field>
              <Field label="Display name">
                <input style={inputStyle} value={profile.displayName || profile.name} onChange={e => set("displayName", e.target.value)} placeholder="Name clients see" />
              </Field>
            </div>
            <Field label="Email address">
              <input style={inputStyle} type="email" value={profile.email} onChange={e => set("email", e.target.value)} placeholder="agent@example.com" />
            </Field>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12 }}>
              <Field label="Mobile" hint="Used for OTP login">
                <input style={inputStyle} value={profile.mobile} onChange={e => set("mobile", e.target.value)} placeholder="+65 9000 0000" />
              </Field>
              <Field label="WhatsApp" hint="Shown to clients">
                <input style={inputStyle} value={profile.whatsapp} onChange={e => set("whatsapp", e.target.value)} placeholder="+65 9000 0000" />
              </Field>
            </div>
            <Field label="Accent colour" hint="Shown on your profile card">
              <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
                {["#84e3f3","#ff697e","#96e7b2","#ff9570","#c084fc","#60a5fa","#f472b6","#34d399"].map(c => (
                  <button key={c} onClick={() => set("accentColor", c)}
                    style={{ all:"unset", cursor:"pointer", width:32, height:32, borderRadius:999, background:c, border: profile.accentColor === c ? "3px solid #f1ece7" : "3px solid transparent", transition:"all 150ms" }} />
                ))}
              </div>
            </Field>
          </div>
        )}

        {step === 1 && (
          <div style={{ display:"grid", gap:14 }}>
            <Field label="Agency / company name">
              <input style={inputStyle} value={profile.agency} onChange={e => set("agency", e.target.value)} placeholder="North Star Advisory" />
            </Field>
            <Field label="Rep code / agent identifier" hint="Your unique referral code on the platform">
              <input style={inputStyle} value={profile.repCode} onChange={e => set("repCode", e.target.value.toUpperCase())} placeholder="MYCODE0001" />
            </Field>
            <Field label="Team leader or supervisor name" hint="Optional — helps us link you to the right agency group">
              <input style={inputStyle} value={profile.teamLeader} onChange={e => set("teamLeader", e.target.value)} placeholder="Team leader name" />
            </Field>
            <Field label="Billing preference">
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:10 }}>
                {[["prepaid","Pre-paid wallet","Top up first, pay as you go"],["postpaid","Post-paid","Billed monthly for confirmed redemptions"]].map(([val, label, sub]) => (
                  <button key={val} onClick={() => set("billingPref", val)}
                    style={{
                      all:"unset", cursor:"pointer", borderRadius:14, padding:"14px 16px",
                      border: profile.billingPref === val ? "1.5px solid #84e3f3" : "1px solid rgba(255,255,255,0.1)",
                      background: profile.billingPref === val ? "rgba(132,227,243,0.1)" : "rgba(255,255,255,0.03)",
                      transition:"all 150ms ease",
                    }}>
                    <div style={{ fontWeight:800, fontSize:"0.9rem", color: profile.billingPref === val ? "#84e3f3" : "#c6cedd" }}>{label}</div>
                    <div style={{ fontSize:"0.73rem", color:"#8b97ab", marginTop:4, lineHeight:1.4 }}>{sub}</div>
                  </button>
                ))}
              </div>
            </Field>
          </div>
        )}

        {step === 2 && (
          <div style={{ display:"grid", gap:16 }}>
            <Field label="Your public bio" hint="Shown on your profile card (max 200 characters)">
              <textarea value={profile.bio} onChange={e => set("bio", e.target.value)} maxLength={200}
                placeholder="I help families make calm, considered decisions about protecting the people they love."
                style={{ ...inputStyle, minHeight:90, resize:"vertical" }} />
              <span style={{ fontSize:"0.7rem", color:"#8b97ab", textAlign:"right" }}>{profile.bio.length}/200</span>
            </Field>
            <div>
              <div style={{ fontWeight:700, fontSize:"0.84rem", color:"#c6cedd", marginBottom:10 }}>Specialties <span style={{ color:"#8b97ab", fontWeight:400 }}>(pick up to 5)</span></div>
              <div style={{ display:"flex", flexWrap:"wrap", gap:8 }}>
                {SPECIALTIES_OPTIONS.map(s => {
                  const on = profile.specialties.includes(s);
                  return (
                    <button key={s} onClick={() => toggleSpecialty(s)}
                      style={{ all:"unset", cursor:"pointer", padding:"6px 14px", borderRadius:999,
                        background: on ? profile.accentColor : "rgba(255,255,255,0.05)",
                        color: on ? "#08111f" : "#8b97ab",
                        border: on ? "none" : "1px solid rgba(255,255,255,0.1)",
                        fontWeight: on ? 800 : 500, fontSize:"0.8rem", transition:"all 150ms",
                      }}>{s}</button>
                  );
                })}
              </div>
            </div>
          </div>
        )}

        {step === 3 && (
          <div style={{ display:"grid", gap:12 }}>
            <div style={{ fontSize:"0.84rem", color:"#8b97ab", marginBottom:4, lineHeight:1.6 }}>
              How should clients connect with you to claim their voucher?
            </div>
            {[
              ["meet","☕","Meet me for tea / coffee","We meet in person before I sponsor the voucher"],
              ["whatsapp","💬","WhatsApp me to claim","Quick digital intro — no in-person required"],
              ["open","🎁","Open gift — no meeting","For existing policyholders or as a free appreciation"],
              ["policyholder","🔒","Existing policyholders only","Only clients who already have a policy with me"],
            ].map(([val, icon, label, sub]) => (
              <button key={val} onClick={() => set("meetingRule", val)}
                style={{
                  all:"unset", cursor:"pointer", borderRadius:16, padding:"14px 16px",
                  border: profile.meetingRule === val ? `1.5px solid ${profile.accentColor}` : "1px solid rgba(255,255,255,0.1)",
                  background: profile.meetingRule === val ? `${profile.accentColor}12` : "rgba(255,255,255,0.03)",
                  display:"flex", gap:12, alignItems:"flex-start", transition:"all 150ms",
                }}>
                <span style={{ fontSize:"1.3rem", marginTop:1 }}>{icon}</span>
                <div>
                  <div style={{ fontWeight:800, fontSize:"0.9rem", color: profile.meetingRule === val ? profile.accentColor : "#c6cedd" }}>{label}</div>
                  <div style={{ fontSize:"0.76rem", color:"#8b97ab", marginTop:3 }}>{sub}</div>
                </div>
              </button>
            ))}
          </div>
        )}

        {step === 4 && (
          <div style={{ display:"grid", gap:18 }}>
            <div style={{ fontSize:"0.84rem", color:"#8b97ab", lineHeight:1.6 }}>
              This is exactly how clients will see your profile card in the marketplace.
            </div>
            <AgentProfileCard profile={previewProfile} compact={false} />
            <div style={{ borderRadius:16, padding:"14px 16px", background:"rgba(132,227,243,0.08)", border:"1px solid rgba(132,227,243,0.2)" }}>
              <div style={{ fontWeight:800, fontSize:"0.84rem", color:"#84e3f3", marginBottom:6 }}>Before you go live:</div>
              <ul style={{ margin:0, padding:"0 0 0 16px", color:"#c6cedd", fontSize:"0.8rem", lineHeight:1.8 }}>
                <li>Your rep code or referral link will be verified by ISPT</li>
                <li>You'll receive a platform slot (1 of 100 at launch)</li>
                <li>Top up your pre-paid wallet or configure a post-paid campaign</li>
              </ul>
            </div>
          </div>
        )}
      </div>

      {/* Nav */}
      <div style={{ display:"flex", gap:10, marginTop:24, paddingTop:16, borderTop:"1px solid rgba(255,255,255,0.07)" }}>
        {step > 0 && (
          <button onClick={() => setStep(step - 1)}
            style={{ all:"unset", cursor:"pointer", padding:"12px 20px", borderRadius:999, border:"1px solid rgba(132,227,243,0.2)", color:"#84e3f3", fontWeight:700, fontSize:"0.88rem" }}>
            ← Back
          </button>
        )}
        <div style={{ flex:1 }} />
        {step < ONBOARDING_STEPS.length - 1 ? (
          <button onClick={() => setStep(step + 1)}
            style={{ all:"unset", cursor:"pointer", padding:"12px 24px", borderRadius:999, background:"#84e3f3", color:"#08111f", fontWeight:800, fontSize:"0.9rem" }}>
            Continue →
          </button>
        ) : (
          <button onClick={() => onComplete(previewProfile)}
            style={{ all:"unset", cursor:"pointer", padding:"12px 24px", borderRadius:999, background:"linear-gradient(90deg,#84e3f3,#96e7b2)", color:"#08111f", fontWeight:800, fontSize:"0.9rem" }}>
            Submit for review ✓
          </button>
        )}
      </div>
    </div>
  );
}

// ── AGENT DASHBOARD ────────────────────────────────────────
function AgentDashboard({ profile }) {
  const [tab, setStab] = useStateA("overview");
  const [collabViewMode, setCollabViewMode] = useStateA("list");
  const accent = profile.accentColor || "#84e3f3";

  const campaigns = [
    { name:"Enchanted Café Tea", voucher:"Pot of Tea · SGD 6", status:"active", claimed:18, redeemed:14, budget:"SGD 108", rule:"Meet for tea" },
    { name:"Petal Pot Birthday", voucher:"10% Flower Voucher", status:"active", claimed:9, redeemed:6, budget:"N/A", rule:"Open gift" },
    { name:"Nail Lab Q1", voucher:"Classic Mani+Pedi · SGD 68", status:"paused", claimed:5, redeemed:3, budget:"SGD 340", rule:"WhatsApp" },
  ];
  const clients = [
    { name:"Sophie Lee", voucher:"Enchanted Café Tea", status:"redeemed", date:"26 Apr 2026" },
    { name:"Joanna Wee", voucher:"Petal Pot Birthday", status:"claimed", date:"25 Apr 2026" },
    { name:"Bryan Tan", voucher:"Nail Lab Q1", status:"claimed", date:"22 Apr 2026" },
    { name:"Michelle Yap", voucher:"Enchanted Café Tea", status:"redeemed", date:"20 Apr 2026" },
  ];
  const agentCollabOffers = RP.AGENT_COLLAB_OFFERS || [];
  const speakerPartners = RP.TALK_PARTNERS || [];
  const relationshipSpaces = RP.RELATIONSHIP_SPACES || [];

  const statusColor = { active:"#96e7b2", paused:"#ff9570", redeemed:"#84e3f3", claimed:"#c4b5fd" };

  return (
    <div style={{ display:"grid", gap:0, height:"100%" }}>
      {/* Stats */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(4,1fr)", gap:10, marginBottom:20 }}>
        {[
          { label:"Wallet balance", val:"SGD 420", sub:"Pre-paid" },
          { label:"Clients linked", val:"47", sub:"All time" },
          { label:"Redemptions", val:"34", sub:"This month" },
          { label:"Redemption rate", val:"89%", sub:"↑ from 82%" },
        ].map((stat, i) => (
          <div key={i} style={{ borderRadius:16, padding:"14px 14px", background:"rgba(255,255,255,0.04)", border:"1px solid rgba(255,255,255,0.08)" }}>
            <div style={{ fontSize:"0.67rem", fontWeight:800, letterSpacing:"0.1em", textTransform:"uppercase", color:"#8b97ab", marginBottom:6 }}>{stat.label}</div>
            <div style={{ fontFamily:"'Barlow Condensed',sans-serif", fontSize:"1.9rem", fontWeight:800, color:accent, lineHeight:1 }}>{stat.val}</div>
            <div style={{ fontSize:"0.7rem", color:"#8b97ab", marginTop:4 }}>{stat.sub}</div>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div style={{ display:"flex", gap:0, borderBottom:"1px solid rgba(255,255,255,0.08)", marginBottom:18 }}>
        {[["overview","Overview"],["campaigns","Campaigns"],["clients","Clients"],["collab","Collaboration"]].map(([id, label]) => (
          <button key={id} onClick={() => setStab(id)}
            style={{ all:"unset", cursor:"pointer", padding:"10px 18px", fontSize:"0.84rem", fontWeight: tab === id ? 800 : 500,
              color: tab === id ? accent : "#8b97ab",
              borderBottom: tab === id ? `2px solid ${accent}` : "2px solid transparent",
              transition:"all 150ms ease",
            }}>{label}</button>
        ))}
      </div>

      {/* Tab content */}
      <div style={{ flex:1, overflowY:"auto" }}>
        {tab === "overview" && (
          <div style={{ display:"grid", gap:14 }}>
            <div style={{ fontSize:"0.84rem", color:"#8b97ab", lineHeight:1.6 }}>Your profile is live. Clients can find you via referral code <span style={{ color:accent, fontWeight:800 }}>{profile.repCode || "MYCODE0001"}</span></div>
            <AgentProfileCard profile={{ ...profile, clientsClaimed: 47, redemptionRate: 89 }} compact={true} />
            <div style={{ borderRadius:14, padding:"14px 16px", background:"rgba(255,255,255,0.03)", border:"1px solid rgba(255,255,255,0.07)" }}>
              <div style={{ fontWeight:800, fontSize:"0.84rem", color:"#c6cedd", marginBottom:10 }}>Quick actions</div>
              <div style={{ display:"flex", flexWrap:"wrap", gap:8 }}>
                {["Gift a voucher","Top up wallet","Run a campaign","View analytics"].map(a => (
                  <button key={a} style={{ all:"unset", cursor:"pointer", padding:"8px 16px", borderRadius:999, border:`1px solid ${accent}33`, color:accent, fontSize:"0.8rem", fontWeight:700 }}>{a}</button>
                ))}
              </div>
            </div>
          </div>
        )}

        {tab === "campaigns" && (
          <div style={{ display:"grid", gap:10 }}>
            {campaigns.map((c, i) => (
              <div key={i} style={{ borderRadius:16, padding:"14px 16px", background:"rgba(255,255,255,0.04)", border:"1px solid rgba(255,255,255,0.08)" }}>
                <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:8 }}>
                  <div>
                    <div style={{ fontWeight:700, color:"#f1ece7", fontSize:"0.9rem" }}>{c.name}</div>
                    <div style={{ fontSize:"0.74rem", color:"#8b97ab", marginTop:2 }}>{c.voucher} · {c.rule}</div>
                  </div>
                  <span style={{ padding:"3px 10px", borderRadius:999, fontSize:"0.7rem", fontWeight:800, background:`${statusColor[c.status]}18`, color:statusColor[c.status] }}>{c.status}</span>
                </div>
                <div style={{ display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:8 }}>
                  {[["Claimed",c.claimed],["Redeemed",c.redeemed],["Budget",c.budget]].map(([label,val]) => (
                    <div key={label}>
                      <div style={{ fontSize:"0.66rem", color:"#8b97ab", fontWeight:800, textTransform:"uppercase", letterSpacing:"0.08em" }}>{label}</div>
                      <div style={{ fontFamily:"'Barlow Condensed',sans-serif", fontSize:"1.3rem", fontWeight:800, color:accent }}>{val}</div>
                    </div>
                  ))}
                </div>
                <div style={{ display:"flex", gap:8, marginTop:12 }}>
                  <button style={{ all:"unset", cursor:"pointer", padding:"6px 14px", borderRadius:999, border:"1px solid rgba(255,255,255,0.1)", color:"#c6cedd", fontSize:"0.76rem" }}>Edit</button>
                  <button style={{ all:"unset", cursor:"pointer", padding:"6px 14px", borderRadius:999, border:"1px solid rgba(255,150,70,0.3)", color:"#ff9570", fontSize:"0.76rem" }}>
                    {c.status === "active" ? "Pause" : "Resume"}
                  </button>
                </div>
              </div>
            ))}
            <button style={{ all:"unset", cursor:"pointer", padding:"14px", borderRadius:16, border:`1px dashed ${accent}44`, color:accent, fontWeight:800, textAlign:"center", fontSize:"0.88rem" }}>
              + New campaign
            </button>
          </div>
        )}

        {tab === "clients" && (
          <div style={{ display:"grid", gap:8 }}>
            {clients.map((c, i) => (
              <div key={i} style={{ borderRadius:14, padding:"12px 14px", background:"rgba(255,255,255,0.04)", border:"1px solid rgba(255,255,255,0.07)", display:"flex", alignItems:"center", gap:12 }}>
                <div style={{ width:36, height:36, borderRadius:10, background:`${accent}22`, display:"grid", placeItems:"center", fontFamily:"'Barlow Condensed',sans-serif", fontWeight:800, color:accent, fontSize:"1rem", flexShrink:0 }}>
                  {c.name.split(" ").map(w=>w[0]).join("")}
                </div>
                <div style={{ flex:1 }}>
                  <div style={{ fontWeight:700, fontSize:"0.88rem", color:"#f1ece7" }}>{c.name}</div>
                  <div style={{ fontSize:"0.73rem", color:"#8b97ab" }}>{c.voucher} · {c.date}</div>
                </div>
                <span style={{ padding:"3px 10px", borderRadius:999, fontSize:"0.69rem", fontWeight:800, background:`${statusColor[c.status]}18`, color:statusColor[c.status] }}>{c.status}</span>
              </div>
            ))}
          </div>
        )}

        {tab === "collab" && (
          <div style={{ display:"grid", gap:12 }}>
            <CollabSectionHeader
              title="Direct Agent Collaboration Offers"
              description="These vendors help insurance agents directly to help their clients."
              controls={<CollabViewModeToggle viewMode={collabViewMode} onChange={setCollabViewMode} />}
            />
            <CollabCollectionView items={agentCollabOffers} accent={accent} viewMode={collabViewMode} />
            {relationshipSpaces.length > 0 && (
              <>
                <CollabSectionHeader
                  title="Intimate spaces to warm up relationships / even close deals"
                  description="These vendors help you warm up relationships and even close deals."
                />
                <CollabCollectionView items={relationshipSpaces} accent={accent} viewMode={collabViewMode} />
              </>
            )}
            {speakerPartners.length > 0 && (
              <>
                <CollabSectionHeader
                  title="Invite speakers to give a talk"
                  eyebrow="Organize a talk and invite speakers / collaborate with merchants to run appreciation events"
                  description="These vendors help you and your team stand out from the competition by giving clients access to wellness and health talks, and giving your team a way to warm up your audience during events."
                />
                <CollabCollectionView items={speakerPartners} accent={accent} viewMode={collabViewMode} />
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// ── MAIN AGENT PORTAL ──────────────────────────────────────
function AgentPortal() {
  const [view, setView] = useStateA("onboarding"); // onboarding | dashboard
  const [completedProfile, setCompletedProfile] = useStateA(null);

  const handleComplete = profile => {
    setCompletedProfile(profile);
    setView("dashboard");
  };

  const demoProfile = RP.AGENTS[0];

  return (
    <div style={{ display:"flex", flexDirection:"column", height:"100vh", overflow:"hidden", fontFamily:"'Manrope','Avenir Next','Segoe UI',sans-serif", background:"linear-gradient(180deg,#0b1829 0%,#060d18 100%)", color:"#f1ece7" }}>
      {/* TOP BAR */}
      <div style={{ display:"flex", alignItems:"center", gap:12, padding:"12px 24px", borderBottom:"1px solid rgba(255,255,255,0.07)", flexShrink:0 }}>
        <div style={{ display:"flex", alignItems:"center", gap:10 }}>
          <BrandLockup subtitle="Agent portal" />
        </div>
        <div style={{ flex:1 }} />
        <div style={{ display:"flex", borderRadius:10, border:"1px solid rgba(255,255,255,0.1)", overflow:"hidden" }}>
          {[["onboarding","Onboarding"],["dashboard","Dashboard"]].map(([id, label]) => (
            <button key={id} onClick={() => setView(id)}
              style={{ all:"unset", cursor:"pointer", padding:"7px 16px", fontSize:"0.82rem",
                background: view === id ? "rgba(132,227,243,0.15)" : "transparent",
                color: view === id ? "#84e3f3" : "#8b97ab",
                borderRight: id !== "dashboard" ? "1px solid rgba(255,255,255,0.08)" : "none",
                transition:"all 150ms ease",
              }}>{label}</button>
          ))}
        </div>
      </div>

      {/* MAIN */}
      <div style={{ flex:1, overflow:"hidden", display:"grid", gridTemplateColumns: view === "onboarding" ? "1fr 400px" : "1fr" }}>
        {view === "onboarding" ? (
          <>
            {/* Left: form */}
            <div style={{ overflowY:"auto", padding:"28px 32px" }}>
              <AgentOnboarding onComplete={handleComplete} />
            </div>
            {/* Right: live preview */}
            <div style={{ borderLeft:"1px solid rgba(255,255,255,0.07)", padding:24, overflowY:"auto", background:"rgba(255,255,255,0.01)" }}>
              <div style={{ fontSize:"0.68rem", fontWeight:800, letterSpacing:"0.14em", textTransform:"uppercase", color:"#8b97ab", marginBottom:16 }}>Live preview — how clients see you</div>
              <AgentProfileCard profile={{ ...RP.AGENTS[0], name:"Your Name", initials:"??", bio:"Fill in your bio…", agency:"Your Agency", specialties:[], accentColor:"#84e3f3" }} compact={false} />
              <div style={{ marginTop:20, borderRadius:14, padding:"12px 14px", background:"rgba(255,255,255,0.03)", border:"1px solid rgba(255,255,255,0.07)" }}>
                <div style={{ fontSize:"0.72rem", fontWeight:800, letterSpacing:"0.1em", color:"#8b97ab", textTransform:"uppercase", marginBottom:8 }}>Launch slots</div>
                <div style={{ fontFamily:"'Barlow Condensed',sans-serif", fontSize:"3rem", fontWeight:800, color:"#84e3f3", lineHeight:1 }}>92<span style={{ fontSize:"1.2rem", color:"#8b97ab" }}>/100</span></div>
                <div style={{ fontSize:"0.76rem", color:"#8b97ab", marginTop:4 }}>Slots remaining at launch. Register early.</div>
                <div style={{ display:"grid", gridTemplateColumns:"repeat(10,1fr)", gap:5, marginTop:14 }}>
                  {Array.from({length:100}).map((_,i) => (
                    <div key={i} style={{ height:10, borderRadius:3, background: i < 8 ? "rgba(132,227,243,0.5)" : "rgba(255,255,255,0.07)" }} />
                  ))}
                </div>
              </div>
            </div>
          </>
        ) : (
          <div style={{ overflowY:"auto", padding:"24px 32px" }}>
            <AgentDashboard profile={completedProfile || demoProfile} />
          </div>
        )}
      </div>
    </div>
  );
}

window.AgentPortal = AgentPortal;
