// ─────────────────────────────────────────────────────────────────────────────
// SalesLab AI — v3.6 (Phase 1.5)
// Updated: 2026-03-14
// Changes:
//   - NEW: Sales IQ Assessment — daily 5-question AI-powered sales scenario test
//   - Sales IQ: 3-step role selector (9 industries × 6+ roles each, including Kitchen & Bath)
//   - Sales IQ: Claude generates role-specific scenarios tailored to industry + role
//   - Sales IQ: Scores 5 skill categories: Discovery, Objection Handling, Closing, Prospecting, Negotiation
//   - Sales IQ: Free users see score + tier + leaderboard rank; Pro users get full skill breakdown
//   - Sales IQ: Viral loop — pre-written LinkedIn post, challenge link, share nudge on dashboard
//   - Sales IQ: 7-day streak tracker, seeded leaderboard, daily reset
//   - Sales IQ: Post-test share card with all skill scores and coaching pills
//   - Sales IQ: Plugged into dashboard home below leaderboard teaser (Pro users only shown full card)
//   - Sales IQ: showSalesIQ state added to main app alongside showGame, showLeaderboard, etc.
//   - Dashboard: Sales IQ card added to home screen with "Take today's test →" CTA
//   - Sales IQ sidebar entry added to PRO_SIDEBAR
// ─────────────────────────────────────────────────────────────────────────────

const { useState, useRef, useEffect } = React;

// ─── Score Color System ───────────────────────────────────────────────────────
// 1–59 red · 60–74 orange · 75–91 yellow · 92–100 green
function scoreColor(score) {
  if (score >= 92) return { text: "#16a34a", bar: "#22c55e", bg: "#f0fdf4", border: "#bbf7d0", label: "Elite" };
  if (score >= 75) return { text: "#b45309", bar: "#f59e0b", bg: "#fffbeb", border: "#fde68a", label: "Strong" };
  if (score >= 60) return { text: "#c2410c", bar: "#f97316", bg: "#fff7ed", border: "#fed7aa", label: "Developing" };
  return           { text: "#dc2626", bar: "#ef4444", bg: "#fef2f2", border: "#fecaca", label: "Needs Work" };
}

// ─── Shuffle Array (Fisher-Yates) ─────────────────────────────────────────────
function shuffleArray(arr) {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}
// MUST be defined first — other constants reference BRAND_CONFIG.appUrl below.
// To white label for a client:
//   1. Duplicate this file
//   2. Update the values below with the client's brand
//   3. Set their own SUPABASE_URL + SUPABASE_ANON_KEY (new Supabase project)
//   4. Set their Stripe links or remove billing and invoice them directly
//   5. Deploy to their subdomain e.g. app.clientname.com
const BRAND_CONFIG = {
  appName:      "SalesLab AI",
  appNameShort: "SalesLab AI",
  tagline:      "TRAIN · TEST · CLOSE",
  logoPath:     "/SalesLab_AI_icon.png",
  appUrl:       "https://thesaleslabai.com",
  supportEmail: "support@thesaleslabai.com",
  primaryColor:  "#0f172a",
  primaryColor2: "#1e293b",
};

// ─── Config ────────────────────────────────────────────────────────────────────
const SUPABASE_URL = "https://nahextkqnsmluuskjxps.supabase.co";
const SUPABASE_ANON_KEY = "sb_publishable_FhMyQlZK8F52DOfjCPlKmQ_ERuR4-cS";
const STRIPE_PRO_LINK   = "https://www.paypal.com/webapps/billing/plans/subscribe?plan_id=P-5Y1401853D764390CNG4Z6GQ";
const STRIPE_TEAM_LINK  = "https://www.paypal.com/webapps/billing/plans/subscribe?plan_id=P-2BB96861PG443164MNG4Z7SA";
const STRIPE_TOPUP_LINK = "https://buy.stripe.com/cNi3cueU35D4dnS8nZcIE06";
const APP_URL = BRAND_CONFIG.appUrl;

// Payment link helper.
// PayPal links get custom_id=userId so the webhook knows which user to activate.
// Stripe topup links get client_reference_id=userId for the same reason.
function stripeLink(baseLink, userId) {
  if (!baseLink.startsWith("https://")) return baseLink;
  if (baseLink.includes("paypal.com")) {
    if (!userId) return baseLink;
    try {
      const url = new URL(baseLink);
      url.searchParams.set("custom_id", userId);
      return url.toString();
    } catch { return baseLink; }
  }
  if (!userId) return baseLink;
  try {
    const url = new URL(baseLink);
    url.searchParams.set("client_reference_id", userId);
    return url.toString();
  } catch { return baseLink; }
}

// ─── Usage Limits ─────────────────────────────────────────────────────────────
const FREE_MAX_PROMPTS_PER_DAY = 5;
const PRO_MAX_TOKENS_PER_MONTH = 300000;
const PRO_TOKEN_WARNING_THRESHOLD = 10000;
const TOKEN_TOPUP_AMOUNT = 300000;

// ─── Supabase Client ──────────────────────────────────────────────────────────
const supabase = (() => {
  const headers = {
    "apikey": SUPABASE_ANON_KEY,
    "Authorization": `Bearer ${SUPABASE_ANON_KEY}`,
    "Content-Type": "application/json",
  };

  const auth = {
    signInWithGoogle: async () => {
      const iqParam = new URLSearchParams(window.location.search).get("iq");
      const redirectBase = `${APP_URL}/app`;
      const redirectTo = iqParam ? `${redirectBase}?iq=${iqParam}` : redirectBase;
      const url = `${SUPABASE_URL}/auth/v1/authorize?provider=google&redirect_to=${encodeURIComponent(redirectTo)}`;
      window.location.href = url;
    },
    signInWithOtp: async (email) => {
      const iqParam = new URLSearchParams(window.location.search).get("iq");
      const redirectTo = iqParam ? `${APP_URL}/app?iq=${iqParam}` : `${APP_URL}/app`;
      const res = await fetch(`${SUPABASE_URL}/auth/v1/otp`, {
        method: "POST",
        headers,
        body: JSON.stringify({ email, create_user: true, options: { emailRedirectTo: redirectTo } }),
      });
      return res.ok;
    },
    getSession: () => {
      try {
        const raw = localStorage.getItem(`sb-${SUPABASE_URL.split("//")[1].split(".")[0]}-auth-token`);
        if (!raw) return null;
        const parsed = JSON.parse(raw);
        if (parsed.expires_at && Date.now() / 1000 > parsed.expires_at) return null;
        return parsed;
      } catch { return null; }
    },
    handleCallback: () => {
      const hash = window.location.hash;
      if (!hash.includes("access_token")) return null;
      const params = new URLSearchParams(hash.replace("#", ""));
      const session = {
        access_token: params.get("access_token"),
        refresh_token: params.get("refresh_token"),
        expires_at: Date.now() / 1000 + parseInt(params.get("expires_in") || "3600"),
        user: { id: params.get("user_id") || "" },
      };
      localStorage.setItem(
        `sb-${SUPABASE_URL.split("//")[1].split(".")[0]}-auth-token`,
        JSON.stringify(session)
      );
      window.history.replaceState({}, document.title, window.location.pathname);
      return session;
    },
    signOut: async () => {
      const session = auth.getSession();
      if (session?.access_token) {
        await fetch(`${SUPABASE_URL}/auth/v1/logout`, {
          method: "POST",
          headers: { ...headers, "Authorization": `Bearer ${session.access_token}` },
        }).catch(() => {});
      }
      localStorage.removeItem(`sb-${SUPABASE_URL.split("//")[1].split(".")[0]}-auth-token`);
    },
    getUser: async (accessToken) => {
      const res = await fetch(`${SUPABASE_URL}/auth/v1/user`, {
        headers: { ...headers, "Authorization": `Bearer ${accessToken}` },
      });
      if (!res.ok) return null;
      return res.json();
    },
  };

  const db = {
    getUserTier: async (userId, accessToken) => {
      try {
        // Step 1: find an active subscription for this user
        const subRes = await fetch(
          `${SUPABASE_URL}/rest/v1/subscriptions?user_id=eq.${userId}&status=eq.active&select=plan_id&limit=1`,
          { headers: { ...headers, "Authorization": `Bearer ${accessToken}` } }
        );
        if (subRes.ok) {
          const subs = await subRes.json();
          if (subs.length && subs[0].plan_id) {
            // Step 2: resolve plan_id → plan name from plans table
            const planRes = await fetch(
              `${SUPABASE_URL}/rest/v1/plans?id=eq.${subs[0].plan_id}&select=name&limit=1`,
              { headers: { ...headers, "Authorization": `Bearer ${accessToken}` } }
            );
            if (planRes.ok) {
              const plans = await planRes.json();
              const name = (plans[0]?.name || "").toLowerCase();
              if (name === "pro" || name === "team") return name;
            }
          }
        }
        // Step 3: fallback — check profiles.plan_id directly
        const profileRes = await fetch(
          `${SUPABASE_URL}/rest/v1/profiles?id=eq.${userId}&select=plan_id,status&limit=1`,
          { headers: { ...headers, "Authorization": `Bearer ${accessToken}` } }
        );
        if (profileRes.ok) {
          const profiles = await profileRes.json();
          const profile = profiles[0];
          if (profile?.plan_id && profile?.status === "active") {
            const planRes2 = await fetch(
              `${SUPABASE_URL}/rest/v1/plans?id=eq.${profile.plan_id}&select=name&limit=1`,
              { headers: { ...headers, "Authorization": `Bearer ${accessToken}` } }
            );
            if (planRes2.ok) {
              const plans2 = await planRes2.json();
              const name2 = (plans2[0]?.name || "").toLowerCase();
              if (name2 === "pro" || name2 === "team") return name2;
            }
          }
        }
      } catch (e) {
        console.warn("[getUserTier] Error:", e);
      }
      return "free";
    },
    upsertUser: async (userId, email, accessToken) => {
      // Upsert into profiles (not users — that table doesn't exist)
      await fetch(`${SUPABASE_URL}/rest/v1/profiles`, {
        method: "POST",
        headers: {
          ...headers,
          "Authorization": `Bearer ${accessToken}`,
          "Prefer": "resolution=merge-duplicates",
        },
        body: JSON.stringify({ id: userId, email }),
      }).catch(() => {});
    },
  };

  return { auth, db };
})();

// ─── Supabase REST helper (replaces supabase.from() calls) ────────────────────
const sbDB = (() => {
  const BASE = SUPABASE_URL + "/rest/v1";
  const getToken = () => {
    try {
      const key = Object.keys(localStorage).find(k => k.startsWith("sb-") && k.endsWith("-auth-token"));
      if (key) {
        const session = JSON.parse(localStorage.getItem(key));
        if (session?.access_token) return session.access_token;
      }
    } catch (e) {}
    return SUPABASE_ANON_KEY;
  };
  const h = () => ({
    "apikey": SUPABASE_ANON_KEY,
    "Authorization": `Bearer ${getToken()}`,
    "Content-Type": "application/json",
    "Prefer": "return=representation",
  });

  const buildUrl = (table, filters = {}, options = {}) => {
    let url = `${BASE}/${table}?`;
    const params = [];
    Object.entries(filters).forEach(([k, v]) => {
      if (typeof v === "object" && v !== null) {
        Object.entries(v).forEach(([op, val]) => params.push(`${k}=${op}.${encodeURIComponent(val)}`));
      } else {
        params.push(`${k}=eq.${encodeURIComponent(v)}`);
      }
    });
    if (options.select) params.push(`select=${options.select}`);
    if (options.order) params.push(`order=${options.order}`);
    if (options.limit) params.push(`limit=${options.limit}`);
    return url + params.join("&");
  };

  return {
    select: async (table, filters = {}, options = {}) => {
      const url = buildUrl(table, filters, options);
      const res = await fetch(url, { headers: h() });
      if (!res.ok) return { data: null, error: await res.text() };
      const data = await res.json();
      if (options.single) return { data: data[0] || null, error: null };
      return { data, error: null };
    },
    insert: async (table, body) => {
      const res = await fetch(`${BASE}/${table}`, {
        method: "POST", headers: h(), body: JSON.stringify(body),
      });
      const data = await res.json().catch(() => null);
      return { data, error: res.ok ? null : data };
    },
    update: async (table, body, filters = {}) => {
      const url = buildUrl(table, filters);
      const res = await fetch(url, {
        method: "PATCH", headers: h(), body: JSON.stringify(body),
      });
      return { error: res.ok ? null : await res.text() };
    },
    upsert: async (table, body, options = {}) => {
      const headers = { ...h(), "Prefer": `resolution=${options.onConflict ? "merge-duplicates" : "merge-duplicates"},return=representation` };
      const res = await fetch(`${BASE}/${table}`, {
        method: "POST", headers, body: JSON.stringify(body),
      });
      return { error: res.ok ? null : await res.text() };
    },
    delete: async (table, filters = {}) => {
      const url = buildUrl(table, filters);
      const res = await fetch(url, { method: "DELETE", headers: h() });
      return { error: res.ok ? null : await res.text() };
    },
    rpc: async (fn, body = {}) => {
      const res = await fetch(`${BASE}/rpc/${fn}`, {
        method: "POST",
        headers: h(),
        body: JSON.stringify(body),
      });
      const data = await res.json().catch(() => null);
      return { data, error: res.ok ? null : (data || "RPC request failed") };
    },
  };
})();

// ─── Usage Tracking Helpers ───────────────────────────────────────────────────
const usageDB = {
  // Get or initialize usage record for a user
  getUsage: async (userId) => {
    const { data } = await sbDB.select("user_usage", { user_id: userId }, { single: true });
    return data;
  },

  // Initialize usage record for new user
  initUsage: async (userId) => {
    const now = new Date().toISOString();
    const dayStart = getDayStart();
    const monthStart = getMonthStart();
    await sbDB.upsert("user_usage", {
      user_id: userId,
      day_start: dayStart,
      prompts_today: 0,
      month_start: monthStart,
      tokens_used_this_month: 0,
      topup_tokens_remaining: 0,
      topup_expires_at: null,
      updated_at: now,
    }, { onConflict: "user_id" });
  },

  // Increment daily prompt count (free users)
  incrementPrompt: async (userId) => {
    const usage = await usageDB.getUsage(userId);
    if (!usage) { await usageDB.initUsage(userId); return; }
    const dayStart = getDayStart();
    const count = usage.day_start === dayStart ? (usage.prompts_today || 0) + 1 : 1;
    await sbDB.update("user_usage", {
      day_start: dayStart,
      prompts_today: count,
      updated_at: new Date().toISOString(),
    }, { user_id: userId });
  },

  // Add token usage (pro/team users)
  addTokens: async (userId, tokensUsed) => {
    const usage = await usageDB.getUsage(userId);
    if (!usage) { await usageDB.initUsage(userId); return; }
    const monthStart = getMonthStart();
    // Reset if new month
    const base = usage.month_start === monthStart ? (usage.tokens_used_this_month || 0) : 0;
    // Deduct from topup first if active
    let topupRemaining = usage.topup_tokens_remaining || 0;
    const topupExpired = !usage.topup_expires_at || new Date() > new Date(usage.topup_expires_at);
    if (topupExpired) topupRemaining = 0;
    await sbDB.update("user_usage", {
      month_start: monthStart,
      tokens_used_this_month: base + tokensUsed,
      topup_tokens_remaining: Math.max(0, topupRemaining - (topupExpired ? 0 : tokensUsed)),
      updated_at: new Date().toISOString(),
    }, { user_id: userId });
  },

  // Apply token top-up after payment
  applyTopup: async (userId) => {
    const expires = new Date();
    expires.setDate(expires.getDate() + 30);
    await sbDB.update("user_usage", {
      topup_tokens_remaining: TOKEN_TOPUP_AMOUNT,
      topup_expires_at: expires.toISOString(),
      updated_at: new Date().toISOString(),
    }, { user_id: userId });
  },
};

function getWeekStart() {
  const d = new Date();
  d.setHours(0, 0, 0, 0);
  d.setDate(d.getDate() - d.getDay()); // Sunday
  return d.toISOString().split("T")[0];
}

function getMonthStart() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-01`;
}

function getNextMonthReset() {
  const d = new Date();
  const next = new Date(d.getFullYear(), d.getMonth() + 1, 1);
  return next.toLocaleString("en-US", { month: "long", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short" });
}

function getNextWeekReset() {
  const d = new Date();
  const daysUntilSunday = 7 - d.getDay();
  const next = new Date(d);
  next.setDate(d.getDate() + daysUntilSunday);
  next.setHours(0, 0, 0, 0);
  return next.toLocaleString("en-US", { weekday: "long", month: "long", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short" });
}

function getDayStart() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`;
}

function getNextDayReset() {
  const next = new Date();
  next.setDate(next.getDate() + 1);
  next.setHours(0, 0, 0, 0);
  return next.toLocaleString("en-US", { weekday: "long", month: "long", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short" });
}


function estimateTokens(text) {
  return Math.ceil((text || "").length / 4);
}

// ─── Free Session Limit Popup ─────────────────────────────────────────────────
function ModuleCopyButton({ text }) {
  const [copied, setCopied] = React.useState(false);
  return (
    <button
      onClick={() => { navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 2000); }}
      style={{ padding: "4px 12px", borderRadius: 6, fontSize: 11, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif", flexShrink: 0, background: copied ? "#f0fdf4" : "transparent", border: copied ? "1px solid #86efac" : "1px solid #e2e8f0", color: copied ? "#16a34a" : "#64748b" }}
    >{copied ? "✓ Copied!" : "Copy"}</button>
  );
}

function FreeSessionLimitModal({ onUpgrade, onClose, userId }) {
  const resetTime = getNextDayReset();
  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "rgba(15,23,42,0.65)", backdropFilter: "blur(6px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
    }}>
      <div style={{
        background: "#ffffff", borderRadius: 20, padding: "32px 28px",
        maxWidth: 440, width: "100%",
        boxShadow: "0 32px 80px rgba(0,0,0,0.2)", border: "1px solid #e2e8f0",
        textAlign: "center",
      }}>
        <div style={{ fontSize: 44, marginBottom: 12 }}>🏁</div>
        <div style={{ fontSize: 20, fontWeight: 800, color: "#0f172a", marginBottom: 8, fontFamily: "'Inter', sans-serif", letterSpacing: "-0.02em" }}>
          You've used your 5 free prompts today.
        </div>
        <div style={{ fontSize: 13.5, color: "#64748b", lineHeight: 1.65, marginBottom: 20, fontFamily: "'Inter', sans-serif" }}>
          Free users get <strong style={{ color: "#0f172a" }}>{FREE_MAX_PROMPTS_PER_DAY} prompts per day</strong>.
          Upgrade to Pro for unlimited access — no daily cap, ever.
        </div>

        <div style={{ padding: "14px 18px", borderRadius: 12, background: "#f8fafc", border: "1px solid #e2e8f0", marginBottom: 20, textAlign: "left" }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.1em", marginBottom: 10 }}>WHAT YOU'RE MISSING ON PRO</div>
          {["🎭 Unlimited roleplay & objection drills", "📊 Close Intelligence Score (0–100)", "📞 Live call coaching & transcript analysis", "🏆 Full deal simulations from intro to close"].map((f, i) => (
            <div key={i} style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 7, fontSize: 12.5, color: "#374151", fontFamily: "'Inter', sans-serif" }}>
              <span>{f}</span>
            </div>
          ))}
        </div>

        <a href={stripeLink(STRIPE_PRO_LINK, userId)} target="_blank" rel="noreferrer" style={{ textDecoration: "none", display: "block", marginBottom: 10 }}>
          <button style={{
            width: "100%", padding: "14px", borderRadius: 11, border: "none",
            background: "linear-gradient(135deg, #1e293b 0%, #0f172a 100%)",
            color: "#fff", fontSize: 14, fontWeight: 700, cursor: "pointer",
            fontFamily: "'Inter', sans-serif", letterSpacing: "0.02em",
          }}>⚡ Upgrade to Pro — $29/mo →</button>
        </a>

        <a href="https://docs.google.com/forms/d/e/1FAIpQLSeOLOobsAywU9nZ3j-s1BC8DdEROWTwzNgBAfkRP5OugFVSVw/viewform?usp=header" target="_blank" rel="noreferrer" style={{ textDecoration: "none", display: "block", marginBottom: 10 }}>
          <button style={{
            width: "100%", padding: "12px", borderRadius: 11, border: "1px solid #e2e8f0",
            background: "#f8fafc", color: "#374151", fontSize: 13, fontWeight: 600, cursor: "pointer",
            fontFamily: "'Inter', sans-serif",
          }}>💰 Make money as an affiliate →</button>
        </a>

        <button onClick={onClose} style={{
          width: "100%", padding: "11px", borderRadius: 10,
          background: "transparent", border: "1px solid #e2e8f0",
          color: "#94a3b8", fontSize: 13, cursor: "pointer", fontFamily: "'Inter', sans-serif",
          marginBottom: 14,
        }}>Not now</button>

        <div style={{ fontSize: 11, color: "#94a3b8", fontFamily: "'Inter', sans-serif", lineHeight: 1.5 }}>
          🔄 Your free prompts reset on <strong style={{ color: "#64748b" }}>{resetTime}</strong>
        </div>
      </div>
    </div>
  );
}

// ─── Free Objection Limit Popup ───────────────────────────────────────────────
function FreeObjLimitModal({ onUpgrade, onClose, userId }) {
  const resetTime = getNextWeekReset();
  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "rgba(15,23,42,0.65)", backdropFilter: "blur(6px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
    }}>
      <div style={{
        background: "#ffffff", borderRadius: 20, padding: "32px 28px",
        maxWidth: 440, width: "100%",
        boxShadow: "0 32px 80px rgba(0,0,0,0.2)", border: "1px solid #e2e8f0",
        textAlign: "center",
      }}>
        <div style={{ fontSize: 44, marginBottom: 12 }}>🎯</div>
        <div style={{ fontSize: 20, fontWeight: 800, color: "#0f172a", marginBottom: 8, fontFamily: "'Inter', sans-serif", letterSpacing: "-0.02em" }}>
          Session complete — nice work!
        </div>
        <div style={{ fontSize: 13.5, color: "#64748b", lineHeight: 1.65, marginBottom: 20, fontFamily: "'Inter', sans-serif" }}>
          You've practiced <strong style={{ color: "#0f172a" }}>{FREE_MAX_OBJECTIONS_PER_SESSION} objections</strong> this session — that's your free limit.
          Start a new session or go Pro for unlimited practice.
        </div>

        <a href={stripeLink(STRIPE_PRO_LINK, userId)} target="_blank" rel="noreferrer" style={{ textDecoration: "none", display: "block", marginBottom: 10 }}>
          <button style={{
            width: "100%", padding: "14px", borderRadius: 11, border: "none",
            background: "linear-gradient(135deg, #1e293b 0%, #0f172a 100%)",
            color: "#fff", fontSize: 14, fontWeight: 700, cursor: "pointer",
            fontFamily: "'Inter', sans-serif",
          }}>⚡ Unlock Unlimited Practice — $29/mo →</button>
        </a>

        <button onClick={onClose} style={{
          width: "100%", padding: "11px", borderRadius: 10,
          background: "transparent", border: "1px solid #e2e8f0",
          color: "#94a3b8", fontSize: 13, cursor: "pointer", fontFamily: "'Inter', sans-serif",
          marginBottom: 14,
        }}>Start new session</button>

        <div style={{ fontSize: 11, color: "#94a3b8", fontFamily: "'Inter', sans-serif", lineHeight: 1.5 }}>
          🔄 Sessions reset <strong style={{ color: "#64748b" }}>{resetTime}</strong>
        </div>
      </div>
    </div>
  );
}

// ─── Pro Token Warning Popup (within 10k of limit) ────────────────────────────
function ProTokenWarningModal({ tokensUsed, onUpgrade, onClose, userId }) {
  const remaining = PRO_MAX_TOKENS_PER_MONTH - tokensUsed;
  const resetTime = getNextMonthReset();
  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "rgba(15,23,42,0.65)", backdropFilter: "blur(6px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
    }}>
      <div style={{
        background: "#ffffff", borderRadius: 20, padding: "32px 28px",
        maxWidth: 460, width: "100%",
        boxShadow: "0 32px 80px rgba(0,0,0,0.2)", border: "1px solid #fde68a",
        textAlign: "center",
      }}>
        <div style={{ fontSize: 44, marginBottom: 12 }}>⚡</div>
        <div style={{ fontSize: 20, fontWeight: 800, color: "#0f172a", marginBottom: 8, fontFamily: "'Inter', sans-serif", letterSpacing: "-0.02em" }}>
          Running low on tokens
        </div>
        <div style={{ fontSize: 13.5, color: "#64748b", lineHeight: 1.65, marginBottom: 6, fontFamily: "'Inter', sans-serif" }}>
          You've used <strong style={{ color: "#0f172a" }}>{tokensUsed.toLocaleString()}</strong> of your <strong style={{ color: "#0f172a" }}>300,000</strong> monthly tokens.
          Only ~<strong style={{ color: "#dc2626" }}>{remaining.toLocaleString()}</strong> left this month.
        </div>

        <div style={{ padding: "12px 16px", borderRadius: 10, background: "#fef9c3", border: "1px solid #fde68a", marginBottom: 20, fontSize: 12.5, color: "#92400e", fontFamily: "'Inter', sans-serif" }}>
          💡 Add <strong>300,000 more tokens</strong> for just <strong>$19</strong> — one-time, no subscription.
          Valid for 30 days from purchase.
        </div>

        <button onClick={onUpgrade} style={{
          width: "100%", padding: "14px", borderRadius: 11, border: "none",
          background: "linear-gradient(135deg, #f59e0b 0%, #d97706 100%)",
          color: "#fff", fontSize: 14, fontWeight: 700, cursor: "pointer",
          fontFamily: "'Inter', sans-serif", marginBottom: 10,
        }}>🚀 Add 300k Tokens — $19 one-time →</button>

        <button onClick={onClose} style={{
          width: "100%", padding: "11px", borderRadius: 10,
          background: "transparent", border: "1px solid #e2e8f0",
          color: "#94a3b8", fontSize: 13, cursor: "pointer", fontFamily: "'Inter', sans-serif",
          marginBottom: 14,
        }}>I'll keep going for now</button>

        <div style={{ fontSize: 11, color: "#94a3b8", fontFamily: "'Inter', sans-serif", lineHeight: 1.5 }}>
          🔄 Your token allowance resets on <strong style={{ color: "#64748b" }}>{resetTime}</strong>
        </div>
      </div>
    </div>
  );
}

// ─── Pro Token Hard Limit Popup ───────────────────────────────────────────────
function ProTokenLimitModal({ onUpgrade, onClose, userId }) {
  const resetTime = getNextMonthReset();
  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "rgba(15,23,42,0.72)", backdropFilter: "blur(6px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
    }}>
      <div style={{
        background: "#0f172a", borderRadius: 20, padding: "32px 28px",
        maxWidth: 460, width: "100%",
        boxShadow: "0 32px 80px rgba(0,0,0,0.4)", border: "1px solid #334155",
        textAlign: "center",
      }}>
        <div style={{ fontSize: 44, marginBottom: 12 }}>🔒</div>
        <div style={{ fontSize: 20, fontWeight: 800, color: "#f1f5f9", marginBottom: 8, fontFamily: "'Inter', sans-serif", letterSpacing: "-0.02em" }}>
          Monthly token limit reached
        </div>
        <div style={{ fontSize: 13.5, color: "#94a3b8", lineHeight: 1.65, marginBottom: 6, fontFamily: "'Inter', sans-serif" }}>
          You've used your <strong style={{ color: "#e2e8f0" }}>300,000 token</strong> monthly allowance.
          Top up to keep training — it's a one-time $19 for another 300k.
        </div>

        <div style={{ padding: "14px 18px", borderRadius: 12, background: "rgba(59,130,246,0.1)", border: "1px solid rgba(59,130,246,0.25)", marginBottom: 20, textAlign: "left" }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: "#93c5fd", letterSpacing: "0.1em", marginBottom: 8 }}>TOKEN TOP-UP DETAILS</div>
          {[
            "✓ +300,000 tokens added instantly",
            "✓ Valid for 30 days from purchase",
            "✓ Resume access immediately after payment",
            "✓ One-time charge — no recurring fees",
          ].map((f, i) => (
            <div key={i} style={{ fontSize: 12.5, color: "#cbd5e1", marginBottom: 6, fontFamily: "'Inter', sans-serif" }}>{f}</div>
          ))}
        </div>

        <a href={stripeLink(STRIPE_TOPUP_LINK, userId)} target="_blank" rel="noreferrer" style={{ textDecoration: "none", display: "block", marginBottom: 10 }}>
          <button style={{
            width: "100%", padding: "14px", borderRadius: 11, border: "none",
            background: "linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)",
            color: "#fff", fontSize: 14, fontWeight: 700, cursor: "pointer",
            fontFamily: "'Inter', sans-serif",
          }}>💳 Add 300k Tokens — $19 →</button>
        </a>

        <button onClick={onClose} style={{
          width: "100%", padding: "11px", borderRadius: 10,
          background: "transparent", border: "1px solid #334155",
          color: "#64748b", fontSize: 13, cursor: "pointer", fontFamily: "'Inter', sans-serif",
          marginBottom: 14,
        }}>Wait for my reset</button>

        <div style={{ fontSize: 11, color: "#475569", fontFamily: "'Inter', sans-serif", lineHeight: 1.5 }}>
          🔄 Free reset on <strong style={{ color: "#94a3b8" }}>{resetTime}</strong>
        </div>
      </div>
    </div>
  );
}

// ─── System Prompts ────────────────────────────────────────────────────────────

const FREE_SYSTEM_PROMPT = `You are ${BRAND_CONFIG.appName} — a practical sales coaching assistant built for two types of salespeople:

1. IN-HOME / SHOWROOM SALES — Kitchen remodeling, flooring, roofing, windows, HVAC, home improvement. These are typically one-call close situations where the salesperson is in the home or showroom with a prospect.

2. SaaS / AE / REMOTE CLOSERS — Account Executives, SDRs, BDRs, remote closers selling software, services, or B2B solutions over the phone or video.

You help with four core areas:

── OBJECTION HANDLING (ACRC Framework) ──
When given an objection, respond using the ACRC framework:
A — Agree: Show empathy and understanding, never argue.
C — Clarify: Ask a short question to understand the real concern.
R — Reframe: Shift focus to value, outcomes, or the cost of inaction.
C — Close: Guide toward the next step naturally.

Always give exact words they can say. Make it sound human and natural, not scripted.

── SCRIPT REWRITING ──
When asked to improve a script or message, provide:
• BEST VERSION — strong, natural, persuasive rewrite
Then ask: "Want an alternate version with a different angle or tone?"

── DISCOVERY QUESTIONS ──
Generate 5–7 concise discovery questions tailored to their product/industry.
Cover: pain points, goals, budget, timeline, decision process, current solutions.
Offer to generate more if needed.

── INTERVIEW PREP ──
Help salespeople prepare for sales job interviews with confident, recruiter-friendly answers.

── FAST COMMANDS ──
Recognize and respond to these shorthand commands instantly:
• ACRC: [objection] — Handle the objection using ACRC
• SCRIPT: [message] — Rewrite the script
• DISCOVERY: [product or situation] — Generate discovery questions
• INTERVIEW: [question] — Give a strong interview answer

── RESPONSE STYLE ──
Keep responses concise and mobile-friendly. Use short paragraphs. Lead with the most useful line first. Avoid long preambles or unnecessary intros. Be direct, confident, and specific. Never give vague or theoretical advice. You are a world-class sales coach.`;

const PRO_SYSTEM_PROMPT = `You are ${BRAND_CONFIG.appName} Pro — an elite sales training and coaching system built specifically for two types of salespeople:

1. IN-HOME / SHOWROOM SALES — Kitchen remodeling, flooring, roofing, windows, HVAC, solar, home improvement. One-call close situations. Price objections, comparison shopping, quote hesitation, in-home pressure dynamics.

2. SaaS / AE / REMOTE CLOSERS — Account Executives, SDRs, BDRs, remote closers. Software demos, discovery calls, multi-stakeholder deals, pipeline management, follow-up sequences, competitive differentiation.

You have three core systems:

── SYSTEM 1: TRAINING ──
• Roleplay Simulator — Play a realistic buyer (skeptical homeowner, rushed executive, price shopper, analytical CFO, etc.). Stay fully in character until user says "Evaluate my responses."
• Buyer Personality Modes — Skeptical Homeowner, Analytical CFO, Aggressive Price Shopper, Rushed Executive, Friendly but Non-Committal, Detail-Oriented Ops Leader
• Full Deal Simulation — Run a complete sales cycle: Prospecting → Discovery → Demo/Presentation → Objections → Negotiation → Close
• Objection Drill Mode — Rapid fire: give objection → user responds → you critique → you improve it
• Objection Library — Price, Timing, Trust, Authority, Competition, Budget, Risk, Vendor Comparison
• Industry Scenarios — In-home remodeling, SaaS, Roofing, HVAC, Solar, Marketing Agencies, Remote Closing
• Framework Trainer — MEDDICC, SPIN Selling, Challenger Sale, Sandler, Consultative Selling, One Call Close

── SYSTEM 2: COACHING ──
• Real-Time Call Coach — User describes what buyer just said, you give exact response + follow-up question + strategy
• Transcript Analyzer — Analyze pasted call transcript: discovery depth, objection handling, talk ratio, missed opportunities, closing attempts
• Deal Coach — Help with stalled deals: identify cause, recommend next move, suggest exact messaging
• Deal Risk Analyzer — Identify risks: weak champion, no budget confirmed, unknown decision process, stalled procurement
• Messaging Coach — Cold calls, voicemails, LinkedIn, email sequences, follow-ups, re-engagement
• Competitive Battlecard — Train against competitor mentions with differentiation scripts
• Cold Outreach Coach — User pastes a cold email or LinkedIn message. Score it 1–10, explain what's weak, then rewrite it. Score the rewrite too. Be blunt.
• Tonality & Pacing Coach — User pastes a script, pitch, or response. Analyze tone: too pushy? too passive? too salesy? too robotic? Give specific word-level edits and explain why. Rate overall tonality.
• Follow-Up Generator — User describes the call outcome and deal stage. Generate 3 tailored follow-up messages: email, text, and voicemail script. Each must be specific to what happened on the call, not generic.

── SYSTEM 3: PERFORMANCE ──
• Performance Reports — Session summary, strengths, areas to improve, sample improved responses
• Close Intelligence Score — Score 0–100 across 7 metrics: Confidence, Clarity, Objection Handling, Discovery Depth, Reframe Strength, Closing Strength, Natural Delivery
• Practice Recommendations — Based on weaknesses, suggest targeted drills
• Session Report Control — Manage and review session history

── SYSTEM 4: TEAM TOOLS (also available to Pro individuals) ──
• Custom Persona Builder — User describes their real buyer (industry, title, objections, personality). Build a detailed custom persona they can roleplay against repeatedly.
• Rep Onboarding Mode — Run a structured 5-session sales training sequence for a new rep. Session 1: Product & ICP. Session 2: Discovery. Session 3: Objection handling. Session 4: Full roleplay. Session 5: Final assessment with score.
• Weekly Performance Summary — User describes their week (calls made, deals moved, objections hit). Generate a structured weekly summary with wins, losses, patterns, and top 3 focus areas for next week.

Also support all FREE features:
• ACRC objection handling
• Script rewrites (Best + Alternate versions)
• Discovery questions
• Interview prep
• Fast commands: ACRC:, SCRIPT:, DISCOVERY:, INTERVIEW:, OUTREACH:, FOLLOWUP:, TONE:

Always stay in character during roleplays. Be direct, challenging, and realistic. When coaching, give specific, actionable language they can use immediately. You are the best sales coach in the world.

── RESPONSE STYLE ──
Keep responses concise and mobile-friendly. Use short paragraphs. Lead with the most useful line first. Avoid long preambles or unnecessary intros. For script rewrites, give one strong Best Version first, then ask if they want an alternate. For discovery questions, generate 5–7 and offer more if needed.`;

// ─── Data ──────────────────────────────────────────────────────────────────────

const FREE_QUICK_PROMPTS = [
  { label: "💬 Handle Objection", prompt: "ACRC: Your price is too high." },
  { label: "✍️ Rewrite My Script", prompt: "SCRIPT: " },
  { label: "🔎 Discovery Questions", prompt: "DISCOVERY: " },
  { label: "💼 Interview Prep", prompt: "INTERVIEW: How do you handle objections?" },
  { label: "🏠 In-Home Objection", prompt: "ACRC: I want to get more quotes before deciding." },
  { label: "💻 SaaS Objection", prompt: "ACRC: We already have a solution in place." },
  { label: "📩 Follow-Up Email", prompt: "SCRIPT: " },
  { label: "🎯 Closing Language", prompt: "Give me 5 natural closing statements for my industry." },
];

const PRO_QUICK_PROMPTS = [
  { label: "🎭 Start Roleplay", prompt: "Start a roleplay scenario." },
  { label: "⚡ Objection Drills", prompt: "Start objection drill mode." },
  { label: "📨 Cold Outreach", prompt: "OUTREACH: [paste your cold email or LinkedIn message here]" },
  { label: "📞 Follow-Up Generator", prompt: "FOLLOWUP: " },
  { label: "🎙️ Tone Coach", prompt: "TONE: [paste your script or pitch here and I'll score it]" },
  { label: "🥊 CFO Roleplay", prompt: "Start a roleplay with an analytical CFO who needs ROI justification." },
  { label: "📋 Transcript Review", prompt: "I want to analyze a sales call transcript. Ready for me to paste it?" },
  { label: "🏆 Close Intel Score", prompt: "Give me my Close Intelligence Score with detailed breakdown." },
];

// ─── Section Page Data ────────────────────────────────────────────────────────
// Each section has subsections with descriptions + auto-prompts

const SECTION_PAGES = {
  // FREE sections (1-4)
  1: {
    id: 1, label: "Objections", icon: "01", proOnly: false,
    desc: "Handle any objection with the ACRC framework — Agree, Clarify, Reframe, Close.",
    subsections: [
      { label: "ACRC Objection Handler", desc: "Use the full ACRC framework to craft a response to any objection your buyer throws at you.", prompt: "ACRC: Your price is too high." },
      { label: "Price Objection", desc: "Get exact words to handle price pushback without caving on your numbers.", prompt: "ACRC: That's more than I wanted to spend." },
      { label: "Think About It", desc: "Keep the deal alive when a prospect stalls with 'I need to think about it.'", prompt: "ACRC: I need to think about it." },
      { label: "Getting More Quotes", desc: "Respond confidently when buyers want to shop around before deciding.", prompt: "ACRC: I'm getting more quotes before I decide." },
      { label: "Send Me Info", desc: "Turn a brush-off request for information into a path toward a real conversation.", prompt: "ACRC: Just send me some information." },
      { label: "Already Have a Vendor", desc: "Handle incumbency objections and open the door to a competitive conversation.", prompt: "ACRC: We already have a solution in place." },
    ]
  },
  2: {
    id: 2, label: "Scripts", icon: "02", proOnly: false,
    desc: "Rewrite any message for clarity, persuasion, and natural delivery.",
    subsections: [
      { label: "Rewrite My Script", desc: "Paste any script, pitch, or message and get a stronger Best Version and an Alternate Version.", prompt: "SCRIPT: " },
      { label: "Follow-Up Message", desc: "Get a follow-up message that re-engages prospects who've gone quiet after a proposal.", prompt: "SCRIPT: " },
      { label: "Cold Outreach", desc: "Generate a targeted cold outreach message for your product or service.", prompt: "SCRIPT: " },
      { label: "Closing Statement", desc: "Get 3–5 natural, pressure-free closing statements you can use at the end of a consultation.", prompt: "Give me 5 natural closing statements for my industry." },
    ]
  },
  3: {
    id: 3, label: "Discovery", icon: "03", proOnly: false,
    desc: "Generate powerful discovery questions tailored to any product or sales situation.",
    subsections: [
      { label: "In-Home Remodeling", desc: "Get 6–10 discovery questions designed for in-home kitchen, flooring, or remodeling consultations.", prompt: "DISCOVERY: " },
      { label: "SaaS / Software", desc: "Uncover pain, budget, timeline, and stakeholders on a software evaluation call.", prompt: "DISCOVERY: " },
      { label: "Remote Closer", desc: "Discovery questions for high-ticket remote closing calls — designed to surface urgency and commitment.", prompt: "DISCOVERY: " },
      { label: "Custom Discovery", desc: "Enter your product and situation and get discovery questions tailored specifically to your sales context.", prompt: "DISCOVERY: " },
    ]
  },
  4: {
    id: 4, label: "Interview Prep", icon: "04", proOnly: false,
    desc: "Prepare for sales job interviews with confident, recruiter-ready answers.",
    subsections: [
      { label: "Sales Process Question", desc: "Walk confidently through your sales process when asked to describe how you sell.", prompt: "INTERVIEW: Tell me about your sales process." },
      { label: "Objection Handling Question", desc: "Answer objection-handling interview questions with a structured, impressive response.", prompt: "INTERVIEW: How do you handle objections?" },
      { label: "Greatest Achievement", desc: "Frame your biggest sales win in a way that showcases skill, not luck.", prompt: "INTERVIEW: What's your greatest sales achievement?" },
      { label: "Why Sales?", desc: "Answer the 'Why sales?' question with conviction and authenticity.", prompt: "INTERVIEW: Why do you want to be in sales?" },
    ]
  },
  // PRO sections (5-8)
  5: {
    id: 5, label: "Training", icon: "05", proOnly: true,
    desc: "Roleplay simulations, objection drills, full deal cycles, and framework training.",
    subsections: [
      { label: "Roleplay Simulator", desc: "Practice against a realistic AI buyer — skeptical homeowner, rushed executive, price shopper, and more.", prompt: "Start a roleplay scenario." },
      { label: "Buyer Personalities", desc: "Choose a specific buyer personality type to practice against for targeted skill-building.", prompt: "Show me available buyer personality modes." },
      { label: "Custom Persona Builder", desc: "Build a custom buyer persona based on your real prospects so you can practice the exact conversations you face.", prompt: "Help me build a custom buyer persona based on my real prospects." },
      { label: "Full Deal Simulation", desc: "Run a complete sales cycle from prospecting through close in one immersive AI simulation.", prompt: "Start a full deal simulation." },
      { label: "Objection Drill Mode", desc: "Rapid-fire objection practice: get an objection, respond, receive critique, see the improved version.", prompt: "Start objection drill mode." },
      { label: "Objection Library", desc: "Train on specific objection categories: price, timing, trust, authority, competition, and more.", prompt: "Train me on price objections." },
      { label: "Industry Scenarios", desc: "Practice industry-specific sales scenarios for remodeling, SaaS, roofing, HVAC, solar, and more.", prompt: "Show me available industry scenario packs." },
      { label: "Framework Trainer", desc: "Train with top sales methodologies: MEDDICC, SPIN, Challenger, Sandler, Consultative Selling.", prompt: "Show me available sales frameworks to train with." },
      { label: "Rep Onboarding", desc: "Complete the structured 5-session onboarding program: Product, Discovery, Objections, Roleplay, Final Assessment.", prompt: "Start the 5-session rep onboarding training program. I'm a new sales rep." },
    ]
  },
  6: {
    id: 6, label: "Coaching", icon: "06", proOnly: true,
    desc: "Real-time call coaching, deal analysis, transcript review, and outreach feedback.",
    subsections: [
      { label: "Cold Outreach Coach", desc: "Paste your cold email or LinkedIn message and get a score, a critique, and a rewritten version.", prompt: "OUTREACH: [paste your cold email or LinkedIn message here]" },
      { label: "Tone & Pacing Coach", desc: "Paste any script or pitch and get a word-level tonality analysis — too pushy? too passive? fix it here.", prompt: "TONE: [paste your script or pitch and I'll score your tonality]" },
      { label: "Follow-Up Generator", desc: "Describe your last call and get three tailored follow-ups: email, text, and voicemail.", prompt: "FOLLOWUP: [describe your last call and where the deal stands]" },
      { label: "Real-Time Call Coach", desc: "Tell me exactly what the buyer just said and get the perfect response plus a follow-up question.", prompt: "I need real-time coaching. The buyer just said they want to compare vendors. What should I say?" },
      { label: "Transcript Analyzer", desc: "Paste a call transcript and get a full breakdown: discovery depth, talk ratio, objection handling, missed opportunities.", prompt: "I want to analyze a sales call transcript. Ready for me to paste it?" },
      { label: "Deal Coach", desc: "Describe a stalled or struggling deal and get a diagnosis, a next-step recommendation, and exact messaging.", prompt: "I need help with a stalled deal." },
      { label: "Deal Risk Analyzer", desc: "Identify the hidden risks in any active deal — weak champion, unclear budget, stalled procurement, and more.", prompt: "Evaluate risk in my current deal." },
      { label: "Messaging Coach", desc: "Get help writing cold calls, voicemails, LinkedIn messages, email sequences, and re-engagement outreach.", prompt: "Help me write outbound sales messaging." },
      { label: "Competitive Battlecard", desc: "Train to respond when a buyer brings up a competitor — get differentiation scripts and positioning language.", prompt: "The buyer says they are considering a competitor. How should I respond?" },
    ]
  },
  7: {
    id: 7, label: "Performance", icon: "07", proOnly: true,
    desc: "Close Intelligence Scores, performance reports, and personalized practice plans.",
    subsections: [
      { label: "Close Intelligence Score", desc: "Get your CIS score (0–100) across 7 metrics: Confidence, Clarity, Objection Handling, Discovery, Reframe, Closing, and Delivery.", prompt: "Give me my Close Intelligence Score with detailed breakdown." },
      { label: "Performance Report", desc: "Generate a session performance report with your strengths, areas to improve, and sample improved responses.", prompt: "Generate a performance report." },
      { label: "Weekly Summary", desc: "Describe your week — calls made, deals moved, objections hit — and get a structured summary with top focus areas.", prompt: "Generate my weekly performance summary. I'll describe my week." },
      { label: "Practice Recommendations", desc: "Get a personalized drill and practice plan based on your current weaknesses and performance patterns.", prompt: "What should I practice based on my weaknesses?" },
    ]
  },
  8: {
    id: 8, label: "Team Tools", icon: "08", proOnly: true,
    desc: "Persona building, rep onboarding, and weekly team performance tracking.",
    subsections: [
      { label: "Custom Persona Builder", desc: "Describe your real buyer — industry, title, typical objections, personality — and build a detailed persona to practice against.", prompt: "Help me build a custom buyer persona based on my real prospects." },
      { label: "Rep Onboarding Mode", desc: "Run a structured 5-session training program for a new rep covering product, discovery, objections, roleplay, and final assessment.", prompt: "Start the 5-session rep onboarding training program. I'm a new sales rep." },
      { label: "Weekly Performance Summary", desc: "Describe your team's week and get a structured summary with wins, patterns, and the top 3 coaching focus areas.", prompt: "Generate a weekly team performance summary. I'll describe the week." },
    ]
  },
};

const FREE_SIDEBAR = [
  { id: 1, label: "Objections", icon: "01" },
  { id: 2, label: "Scripts", icon: "02" },
  { id: 3, label: "Discovery", icon: "03" },
  { id: 4, label: "Interview Prep", icon: "04" },
  { id: 10, label: "Profit Engine", icon: "💰", isProfitEngine: true },
  { id: 5, label: "Training", icon: "05", proOnly: true },
  { id: 6, label: "Coaching", icon: "06", proOnly: true },
  { id: 7, label: "Performance", icon: "07", proOnly: true },
  { id: 9, label: "Close or Lose", icon: "⚔️", proOnly: true, isGame: true },
];

const PRO_SIDEBAR = [
  { id: 9, label: "Close or Lose", icon: "⚔️", isGame: true },
  { id: 10, label: "Profit Engine", icon: "💰", isProfitEngine: true },
  { id: 11, label: "Sales IQ", icon: "⚡", isSalesIQ: true },
  { id: 5, label: "Training", icon: "01" },
  { id: 6, label: "Coaching", icon: "02" },
  { id: 7, label: "Performance", icon: "03" },
  { id: 1, label: "Objections", icon: "04" },
  { id: 2, label: "Scripts", icon: "05" },
  { id: 3, label: "Discovery", icon: "06" },
  { id: 4, label: "Interview Prep", icon: "07" },
  { id: 8, label: "Team Tools", icon: "08" },
];


// ─── Close or Lose — Seed Leaderboard ────────────────────────────────────────
const SEED_USERS = [
  { name: "Marcus Webb", title: "Sr. Account Executive", location: "Dallas, TX", score: 94, scenarios: 31, winRate: 88 },
  { name: "Priya Nair", title: "In-Home Sales Rep", location: "Phoenix, AZ", score: 91, scenarios: 28, winRate: 85 },
  { name: "Tyler Johansson", title: "Remote Closer", location: "Austin, TX", score: 90, scenarios: 26, winRate: 84 },
  { name: "Danielle Cross", title: "SaaS Account Executive", location: "Chicago, IL", score: 89, scenarios: 24, winRate: 82 },
  { name: "Kevin Okafor", title: "Flooring Sales Consultant", location: "Atlanta, GA", score: 88, scenarios: 22, winRate: 81 },
  { name: "Sofia Reyes", title: "Solar Sales Rep", location: "San Diego, CA", score: 87, scenarios: 29, winRate: 80 },
  { name: "James Whitfield", title: "Enterprise AE", location: "New York, NY", score: 86, scenarios: 19, winRate: 79 },
  { name: "Alicia Monroe", title: "Kitchen Remodel Specialist", location: "Houston, TX", score: 85, scenarios: 21, winRate: 78 },
  { name: "Derek Sung", title: "SDR to AE", location: "Seattle, WA", score: 84, scenarios: 17, winRate: 77 },
  { name: "Natasha Bright", title: "HVAC Sales Rep", location: "Denver, CO", score: 83, scenarios: 23, winRate: 76 },
  { name: "Brandon Tate", title: "Roofing Sales Closer", location: "Nashville, TN", score: 82, scenarios: 18, winRate: 75 },
  { name: "Camille Durant", title: "B2B Sales Executive", location: "Miami, FL", score: 81, scenarios: 15, winRate: 74 },
  { name: "Josh Kimura", title: "Inside Sales Rep", location: "Portland, OR", score: 80, scenarios: 20, winRate: 73 },
  { name: "Rachel Torres", title: "Window & Door Sales", location: "Las Vegas, NV", score: 79, scenarios: 14, winRate: 72 },
  { name: "Antonio Ferreira", title: "Account Manager", location: "Boston, MA", score: 78, scenarios: 16, winRate: 71 },
  { name: "Hannah Lowe", title: "Flooring Sales Rep", location: "Charlotte, NC", score: 77, scenarios: 12, winRate: 70 },
  { name: "Miles Patterson", title: "Remote Sales Closer", location: "Tampa, FL", score: 76, scenarios: 13, winRate: 69 },
  { name: "Zoe Chambers", title: "SaaS BDR", location: "Austin, TX", score: 75, scenarios: 11, winRate: 68 },
  { name: "Chris Navarro", title: "Home Improvement Sales", location: "Sacramento, CA", score: 74, scenarios: 18, winRate: 67 },
  { name: "Tiffany Brooks", title: "Insurance Sales Rep", location: "Columbus, OH", score: 73, scenarios: 10, winRate: 66 },
  { name: "Elijah Grant", title: "Solar Consultant", location: "Scottsdale, AZ", score: 72, scenarios: 9, winRate: 65 },
  { name: "Megan Schultz", title: "AE Mid Market", location: "Minneapolis, MN", score: 71, scenarios: 14, winRate: 64 },
  { name: "Ryan Castillo", title: "Remodeling Sales Rep", location: "San Antonio, TX", score: 70, scenarios: 8, winRate: 63 },
  { name: "Diana Pham", title: "Tech Sales Rep", location: "San Jose, CA", score: 69, scenarios: 11, winRate: 62 },
  { name: "Noah Henderson", title: "HVAC Comfort Advisor", location: "Indianapolis, IN", score: 68, scenarios: 7, winRate: 61 },
  { name: "Keisha Williams", title: "Direct Sales Rep", location: "Detroit, MI", score: 67, scenarios: 12, winRate: 60 },
  { name: "Owen Fitzgerald", title: "Roofing Estimator", location: "Kansas City, MO", score: 66, scenarios: 6, winRate: 59 },
  { name: "Leila Hassan", title: "SDR", location: "Austin, TX", score: 65, scenarios: 9, winRate: 58 },
  { name: "Travis Moon", title: "Home Security Sales", location: "Salt Lake City, UT", score: 64, scenarios: 8, winRate: 57 },
  { name: "Vanessa Cox", title: "Flooring Specialist", location: "Raleigh, NC", score: 63, scenarios: 7, winRate: 56 },
  { name: "Adam Reyes", title: "Outside Sales Rep", location: "El Paso, TX", score: 62, scenarios: 5, winRate: 55 },
  { name: "Brianna Scott", title: "Solar Sales Advisor", location: "Albuquerque, NM", score: 61, scenarios: 6, winRate: 54 },
  { name: "Darius Cole", title: "Pest Control Sales", location: "Memphis, TN", score: 60, scenarios: 4, winRate: 53 },
  { name: "Penny Larson", title: "Real Estate Agent", location: "Richmond, VA", score: 59, scenarios: 7, winRate: 52 },
  { name: "Garrett Howell", title: "Windows Sales Rep", location: "Louisville, KY", score: 58, scenarios: 5, winRate: 51 },
  { name: "Simone Archer", title: "Med Device Sales", location: "Cincinnati, OH", score: 57, scenarios: 6, winRate: 50 },
  { name: "Luke Brennan", title: "In-Home Sales Rep", location: "Oklahoma City, OK", score: 56, scenarios: 4, winRate: 49 },
  { name: "Tara Nguyen", title: "SaaS Sales Rep", location: "San Francisco, CA", score: 55, scenarios: 5, winRate: 48 },
  { name: "Corey Banks", title: "Alarm Sales Rep", location: "Jacksonville, FL", score: 54, scenarios: 3, winRate: 47 },
  { name: "Isabel Moreau", title: "Kitchen Sales Specialist", location: "New Orleans, LA", score: 53, scenarios: 4, winRate: 46 },
  { name: "Jalen Pierce", title: "Auto Sales Rep", location: "Detroit, MI", score: 52, scenarios: 3, winRate: 45 },
  { name: "Chloe Barrett", title: "B2B Sales Associate", location: "Pittsburgh, PA", score: 51, scenarios: 4, winRate: 44 },
  { name: "Marcus Holt", title: "Remote Closer", location: "Boise, ID", score: 50, scenarios: 3, winRate: 43 },
  { name: "Nina Caldwell", title: "Field Sales Rep", location: "Tucson, AZ", score: 49, scenarios: 2, winRate: 42 },
  { name: "Reggie Stone", title: "Solar Rep", location: "Fresno, CA", score: 48, scenarios: 3, winRate: 41 },
  { name: "Alexis Ford", title: "Inside Sales", location: "Omaha, NE", score: 47, scenarios: 2, winRate: 40 },
  { name: "Dominic Shaw", title: "Remodeling Consultant", location: "Tulsa, OK", score: 46, scenarios: 2, winRate: 39 },
  { name: "Jasmine Reid", title: "Sales Development Rep", location: "Richmond, VA", score: 45, scenarios: 2, winRate: 38 },
  { name: "Brady Walsh", title: "Entry Level AE", location: "Buffalo, NY", score: 44, scenarios: 1, winRate: 37 },
  { name: "Sierra Long", title: "New Sales Rep", location: "Springfield, IL", score: 43, scenarios: 1, winRate: 36 },
];

function getGameWeekStart() {
  const d = new Date();
  d.setHours(0, 0, 0, 0);
  d.setDate(d.getDate() - d.getDay());
  return d.toISOString().split("T")[0];
}

function getNextSundayReset() {
  const d = new Date();
  const daysUntil = 7 - d.getDay();
  const next = new Date(d);
  next.setDate(d.getDate() + daysUntil);
  next.setHours(0, 0, 0, 0);
  return next.toLocaleDateString("en-US", { weekday: "long", month: "short", day: "numeric" });
}

// ─── Close or Lose v2 — Configs ──────────────────────────────────────────────

const COL_INDUSTRIES = [
  { id: "saas", label: "SaaS / Tech", icon: "💻" },
  { id: "solar", label: "Solar", icon: "☀️" },
  { id: "remodeling", label: "In-Home Remodeling", icon: "🏠" },
  { id: "roofing", label: "Roofing", icon: "🏗️" },
  { id: "insurance", label: "Insurance", icon: "🛡️" },
  { id: "other", label: "Other", icon: "💼" },
];

const COL_ROLES = [
  { id: "ae", label: "Account Executive" },
  { id: "sdr", label: "SDR / BDR" },
  { id: "remote_closer", label: "Remote Closer" },
  { id: "in_home", label: "In-Home Closer" },
  { id: "appointment_setter", label: "Appointment Setter" },
  { id: "other", label: "Other" },
];

const COL_PERSONALITIES = [
  { id: "analytical", label: "Analytical", desc: "Asks for data, ROI, proof" },
  { id: "skeptical", label: "Skeptical", desc: "Questions everything" },
  { id: "friendly", label: "Friendly", desc: "Warm but non-committal" },
  { id: "dominant", label: "Dominant", desc: "Challenges claims directly" },
  { id: "price_sensitive", label: "Price Sensitive", desc: "Every conversation returns to cost" },
];

// Mode 1 – Speed Close rounds
const MODE1_ROUNDS = [
  { round: 1, difficulty: "Soft Hesitation", diffColor: "#22c55e", label: "Round 1", objection: "This sounds interesting but I don't think the timing is right for us.", skillTested: "Uncovering the real hesitation and creating urgency without pressure." },
  { round: 2, difficulty: "Price Concern", diffColor: "#3b82f6", label: "Round 2", objection: "The price is higher than what we budgeted for this.", skillTested: "Reframing value against cost without discounting." },
  { round: 3, difficulty: "Competitor Comparison", diffColor: "#f59e0b", label: "Round 3", objection: "We're already in conversations with two of your competitors and they're cheaper.", skillTested: "Differentiating specifically without attacking the competition." },
  { round: 4, difficulty: "Decision Delay", diffColor: "#f97316", label: "Round 4", objection: "We like what we see but we need to think it over and loop in a few more people.", skillTested: "Pulling the decision forward and identifying the real stall." },
  { round: 5, difficulty: "Boss Round", diffColor: "#ef4444", label: "Boss Round", objection: "The price is too high, we need leadership approval, and honestly I'm not sure this is the right time.", skillTested: "Handling three objections at once and landing a confident close." },
];

// Mode 2 – Full Dialogue rounds (multi-turn)
const MODE2_ROUNDS = [
  {
    round: 1, difficulty: "Discovery Resistance", diffColor: "#22c55e", label: "Round 1",
    openingObjection: "We're not really looking to make any changes right now. Things are working fine.",
    followUps: [
      "I hear you but I don't see a compelling reason to switch from what we have.",
      "What makes you think we have a problem that needs solving?",
      "We've looked at solutions like this before and it never worked out.",
      "Even if there's a better way, the disruption of changing isn't worth it right now.",
      "Our team is already stretched thin. Adding something new would just create more work.",
    ],
    skillsTested: ["Discovery questions", "Establishing curiosity", "Early conversation control"],
    maxExchanges: 3,
  },
  {
    round: 2, difficulty: "Objection Battle", diffColor: "#f59e0b", label: "Round 2",
    openingObjection: "Your price is higher than what we're paying now and higher than what your competitors quoted us.",
    followUps: [
      "I'd need to justify this cost increase to my CFO and I'm not sure I can.",
      "Unless you can match the price, I'm not sure there's a deal here.",
      "What exactly am I paying more for? Because on paper it looks the same.",
      "Our budget is locked until next quarter. Even if I wanted to move forward I couldn't.",
      "I've been burned before by paying more for something that didn't deliver. Why is this different?",
    ],
    skillsTested: ["Layered objection handling", "Maintaining authority", "Value positioning"],
    maxExchanges: 4,
  },
  {
    round: 3, difficulty: "Closing Scenario", diffColor: "#ef4444", label: "Boss Round",
    openingObjection: "We appreciate the pitch but the timing isn't right. We're in the middle of a budget freeze.",
    followUps: [
      "Even if we wanted to move forward, getting leadership to approve this right now would be a fight.",
      "A competitor offered us a better price and said they can wait until next quarter.",
      "I don't have the authority to sign off on this. It needs to go up the chain and that takes time.",
      "Look, I like what you're offering but I can't commit today. That's just not happening.",
      "We've had vendors push us to move fast before and it always ends badly. I'm not doing that again.",
      "Send me something in writing and I'll share it with the team. But don't expect a quick answer.",
    ],
    skillsTested: ["Confidence under pressure", "Multi-objection management", "Closing the deal"],
    maxExchanges: 6,
  },
];

function getPersonalizedObjection(objection, industry, personality) {
  const industryCtx = {
    saas: "software solution", solar: "solar system", remodeling: "remodeling project",
    roofing: "roofing job", insurance: "insurance policy", other: "product",
  };
  const ctx = industryCtx[industry] || "product";
  let personalized = objection.replace(/product|solution|system/gi, ctx);

  // Personality flavoring — only applied when the objection doesn't already
  // contain a personality-specific phrase, so it never repeats the same suffix.
  const analyticalSuffixes = [
    " What does the data actually support?",
    " I need to see the numbers before I can commit.",
    " Do you have case studies to back that up?",
    " What's the measurable ROI here?",
    " Walk me through the specifics.",
  ];
  const dominantSuffixes = [
    ", and I've seen better offers.",
    " Don't waste my time.",
    " I need a reason to move forward today.",
    " Make your case quickly.",
    " I'm not easily convinced.",
  ];
  const priceSuffixes = [
    " I need to know I'm getting the best deal possible.",
    " I've been quoted lower elsewhere.",
    " What's the best you can do on price?",
    " I'm not paying more than I have to.",
    " Price is my number one concern here.",
  ];

  const alreadyFlavored = (suffix) => suffixes => suffixes.some(s => personalized.includes(s.trim()));

  if (personality === "analytical" && !analyticalSuffixes.some(s => personalized.includes(s.trim()))) {
    personalized += analyticalSuffixes[Math.floor(Math.random() * analyticalSuffixes.length)];
  }
  if (personality === "dominant" && !dominantSuffixes.some(s => personalized.includes(s.trim()))) {
    const suffix = dominantSuffixes[Math.floor(Math.random() * dominantSuffixes.length)];
    personalized = personalized.replace(/\.$/, "") + suffix;
  }
  if (personality === "price_sensitive" && !priceSuffixes.some(s => personalized.includes(s.trim()))) {
    personalized += priceSuffixes[Math.floor(Math.random() * priceSuffixes.length)];
  }
  return personalized;
}

// ─── Profile Setup Modal ──────────────────────────────────────────────────────
function GameProfileModal({ onSave, onCancel, existing }) {
  const [name, setName] = useState(existing?.name || "");
  const [title, setTitle] = useState(existing?.title || "");
  const [location, setLocation] = useState(existing?.location || "");
  const [photo, setPhoto] = useState(existing?.photo || null);
  const fileRef = useRef(null);

  const handlePhoto = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => setPhoto(ev.target.result);
    reader.readAsDataURL(file);
  };

  const canSave = name.trim() && title.trim() && location.trim();

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 200, background: "rgba(15,23,42,0.5)", backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20, fontFamily: "'Inter', sans-serif" }}>
      <div style={{ background: "#ffffff", borderRadius: 16, padding: "32px 28px", maxWidth: 420, width: "100%", border: "1px solid #e2e8f0", boxShadow: "0 20px 60px rgba(15,23,42,0.15)", position: "relative" }}>
        {onCancel && (
          <button onClick={onCancel} style={{ position: "absolute", top: 14, right: 16, background: "none", border: "none", color: "#94a3b8", fontSize: 22, cursor: "pointer", lineHeight: 1, padding: "2px 6px" }}>×</button>
        )}
        <div style={{ textAlign: "center", marginBottom: 24 }}>
          <div style={{ fontSize: 28, marginBottom: 8 }}>⚔️</div>
          <div style={{ fontSize: 18, fontWeight: 800, color: "#0f172a", marginBottom: 6 }}>{existing ? "Edit Your Profile" : "Set Up Your Player Profile"}</div>
          <div style={{ fontSize: 13, color: "#64748b" }}>{existing ? "Update your name, title, or location." : "This will appear on your scorecard when you share your results."}</div>
        </div>
        <div style={{ display: "flex", justifyContent: "center", marginBottom: 8 }}>
          <div onClick={() => fileRef.current?.click()} style={{ width: 72, height: 72, borderRadius: "50%", background: "#f8fafc", border: "2px dashed #cbd5e1", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", overflow: "hidden" }}>
            {photo ? <img src={photo} alt="profile" style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : <span style={{ fontSize: 24 }}>📷</span>}
          </div>
          <input ref={fileRef} type="file" accept="image/*" onChange={handlePhoto} style={{ display: "none" }} />
        </div>
        <div style={{ textAlign: "center", fontSize: 11, color: "#94a3b8", marginBottom: 20 }}>Tap to add a photo (optional)</div>
        {[
          { label: "FULL NAME", val: name, set: setName, placeholder: "e.g. James Carter" },
          { label: "JOB TITLE", val: title, set: setTitle, placeholder: "e.g. Enterprise Account Executive" },
          { label: "LOCATION", val: location, set: setLocation, placeholder: "e.g. Austin, TX" },
        ].map((f, i) => (
          <div key={i} style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.12em", marginBottom: 6 }}>{f.label}</div>
            <input value={f.val} onChange={e => f.set(e.target.value)} placeholder={f.placeholder} style={{ width: "100%", padding: "10px 14px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#f8fafc", color: "#0f172a", fontSize: 13, fontFamily: "'Inter', sans-serif", outline: "none", boxSizing: "border-box" }} />
          </div>
        ))}
        <button onClick={() => canSave && onSave({ name: name.trim(), title: title.trim(), location: location.trim(), photo })} disabled={!canSave} style={{ width: "100%", padding: "13px", borderRadius: 10, border: "none", background: canSave ? "#0f172a" : "#f1f5f9", color: canSave ? "#fff" : "#94a3b8", fontSize: 14, fontWeight: 700, cursor: canSave ? "pointer" : "not-allowed", marginTop: 4 }}>
          Let's Play ⚔️
        </button>
      </div>
    </div>
  );
}

// ─── Mode Selection Screen ────────────────────────────────────────────────────
function ModeSelectScreen({ onSelect, onExit, topScore, totalPlayers, isPro, onViewLeaderboard }) {
  const modes = [
    { id: 1, icon: "⚡", name: "Speed Close", tag: "5 rounds · Fast", desc: "One objection per round. Score each response. See how you stack up.", color: "#3b82f6", free: false },
    { id: 2, icon: "⚔️", name: "Close or Lose", tag: "3 rounds · Full simulation", desc: "Multi-turn conversations with a live AI buyer. Handle every layer.", color: "#f97316", free: false },
    { id: 3, icon: "🔥", name: "Streak Mode", tag: "PRO · Endless", desc: "Win back-to-back deals. One loss resets your streak.", color: "#ef4444", free: false, proOnly: true },
  ];
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 150, background: "#f1f5f9", display: "flex", flexDirection: "column", fontFamily: "'Inter', sans-serif" }}>
      <div style={{ paddingTop: "env(safe-area-inset-top)", paddingLeft: 24, paddingRight: 24, paddingBottom: 14, borderBottom: "1px solid #e2e8f0", background: "#fff", display: "flex", alignItems: "center", justifyContent: "space-between", flexShrink: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ fontSize: 16 }}>⚔️</span>
          <span style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>Close or Lose</span>
          <span style={{ fontSize: 9, background: "#fef2f2", color: "#ef4444", border: "1px solid #fecaca", borderRadius: 4, padding: "2px 7px", fontWeight: 700 }}>PRO</span>
        </div>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <button onClick={onViewLeaderboard} style={{ background: "none", border: "1px solid #e2e8f0", borderRadius: 6, padding: "5px 12px", fontSize: 11, color: "#64748b", cursor: "pointer" }}>🏆 Leaderboard</button>
          <button onClick={onExit} style={{ background: "transparent", border: "1px solid #e2e8f0", color: "#94a3b8", borderRadius: 6, padding: "5px 14px", fontSize: 11, cursor: "pointer" }}>← Back</button>
        </div>
      </div>
      <div style={{ flex: 1, overflowY: "auto", padding: "28px 24px", display: "flex", flexDirection: "column", alignItems: "center" }}>
        <div style={{ maxWidth: 520, width: "100%" }}>
          <div style={{ textAlign: "center", marginBottom: 24 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: "#0f172a", marginBottom: 4 }}>Choose Your Mode</div>
            <div style={{ fontSize: 12, color: "#94a3b8" }}>Top score this week: <strong style={{ color: scoreColor(topScore).text }}>{topScore}</strong> · {totalPlayers}+ reps competing</div>
          </div>
          {modes.map((m) => (
            <button key={m.id} onClick={() => onSelect(m.id)} style={{ width: "100%", marginBottom: 10, padding: "18px 20px", borderRadius: 12, background: "#ffffff", border: `1.5px solid #e2e8f0`, cursor: "pointer", textAlign: "left", fontFamily: "'Inter', sans-serif", display: "flex", alignItems: "center", gap: 16, transition: "border-color 0.15s" }}
              onMouseEnter={e => e.currentTarget.style.borderColor = m.color}
              onMouseLeave={e => e.currentTarget.style.borderColor = "#e2e8f0"}>
              <div style={{ width: 44, height: 44, borderRadius: 10, background: `${m.color}15`, border: `1px solid ${m.color}30`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 20, flexShrink: 0 }}>{m.icon}</div>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 3 }}>
                  <span style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>{m.name}</span>
                  <span style={{ fontSize: 9, fontWeight: 700, color: m.color, background: `${m.color}12`, border: `1px solid ${m.color}25`, borderRadius: 4, padding: "1px 6px" }}>{m.tag}</span>
                  {m.proOnly && <span style={{ fontSize: 9, fontWeight: 700, color: "#f59e0b", background: "#fffbeb", border: "1px solid #fde68a", borderRadius: 4, padding: "1px 6px" }}>PRO ONLY</span>}
                </div>
                <div style={{ fontSize: 12, color: "#64748b" }}>{m.desc}</div>
              </div>
              <span style={{ fontSize: 16, color: "#cbd5e1", flexShrink: 0 }}>→</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─── Game Setup Screen (Industry + Role + Personality) ────────────────────────
function GameSetupScreen({ mode, onStart, onBack }) {
  const [industry, setIndustry] = useState(null);
  const [role, setRole] = useState(null);
  const [personality] = useState(() => COL_PERSONALITIES[Math.floor(Math.random() * COL_PERSONALITIES.length)]);
  const canStart = industry && role;

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 150, background: "#f1f5f9", display: "flex", flexDirection: "column", fontFamily: "'Inter', sans-serif" }}>
      <div style={{ paddingTop: "env(safe-area-inset-top)", paddingLeft: 24, paddingRight: 24, paddingBottom: 14, borderBottom: "1px solid #e2e8f0", background: "#fff", display: "flex", alignItems: "center", justifyContent: "space-between", flexShrink: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ fontSize: 13 }}>⚔️</span>
          <span style={{ fontSize: 13, fontWeight: 700, color: "#0f172a" }}>
            {mode === 1 ? "⚡ Speed Close" : mode === 2 ? "⚔️ Close or Lose" : "🔥 Streak Mode"} — Setup
          </span>
        </div>
        <button onClick={onBack} style={{ background: "transparent", border: "1px solid #e2e8f0", color: "#94a3b8", borderRadius: 6, padding: "5px 12px", fontSize: 11, cursor: "pointer" }}>← Back</button>
      </div>
      <div style={{ flex: 1, overflowY: "auto", padding: "24px", display: "flex", flexDirection: "column", alignItems: "center" }}>
        <div style={{ maxWidth: 500, width: "100%" }}>
          {/* Industry */}
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.12em", marginBottom: 10 }}>YOUR INDUSTRY</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
              {COL_INDUSTRIES.map(ind => (
                <button key={ind.id} onClick={() => setIndustry(ind.id)} style={{ padding: "10px 8px", borderRadius: 10, border: `1.5px solid ${industry === ind.id ? "#0f172a" : "#e2e8f0"}`, background: industry === ind.id ? "#0f172a" : "#fff", color: industry === ind.id ? "#fff" : "#475569", fontSize: 11, fontWeight: 600, cursor: "pointer", textAlign: "center", fontFamily: "'Inter', sans-serif" }}>
                  <div style={{ fontSize: 16, marginBottom: 3 }}>{ind.icon}</div>
                  {ind.label}
                </button>
              ))}
            </div>
          </div>
          {/* Role */}
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.12em", marginBottom: 10 }}>YOUR ROLE</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
              {COL_ROLES.map(r => (
                <button key={r.id} onClick={() => setRole(r.id)} style={{ padding: "10px 14px", borderRadius: 10, border: `1.5px solid ${role === r.id ? "#0f172a" : "#e2e8f0"}`, background: role === r.id ? "#0f172a" : "#fff", color: role === r.id ? "#fff" : "#475569", fontSize: 12, fontWeight: 600, cursor: "pointer", textAlign: "left", fontFamily: "'Inter', sans-serif" }}>
                  {r.label}
                </button>
              ))}
            </div>
          </div>
          {/* Personality reveal */}
          <div style={{ marginBottom: 24, padding: "14px 16px", borderRadius: 12, background: "#fff", border: "1px solid #e2e8f0" }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.12em", marginBottom: 8 }}>YOUR BUYER TODAY</div>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ width: 40, height: 40, borderRadius: 8, background: "#f1f5f9", border: "1px solid #e2e8f0", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 18, flexShrink: 0 }}>🎭</div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 700, color: "#0f172a", marginBottom: 2 }}>{personality.label} Buyer</div>
                <div style={{ fontSize: 11, color: "#64748b" }}>{personality.desc}</div>
              </div>
            </div>
          </div>
          <button onClick={() => canStart && onStart({ industry, role, personality: personality.id })} disabled={!canStart} style={{ width: "100%", padding: "14px", borderRadius: 10, border: "none", background: canStart ? "#0f172a" : "#f1f5f9", color: canStart ? "#fff" : "#94a3b8", fontSize: 14, fontWeight: 700, cursor: canStart ? "pointer" : "not-allowed" }}>
            {canStart ? "Start Game →" : "Select Industry & Role to Continue"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Close or Lose — Main Game ────────────────────────────────────────────────
function CloseOrLoseGame({ currentUser, onExit, isPro }) {
  const [profile, setProfile] = useState(() => { try { return JSON.parse(localStorage.getItem("col_profile") || "null"); } catch { return null; } });
  const [screen, setScreen] = useState("modeSelect"); // modeSelect | setup | playing | scoring | scorecard | leaderboard
  const [selectedMode, setSelectedMode] = useState(null); // 1 | 2 | 3
  const [setupConfig, setSetupConfig] = useState(null); // { industry, role, personality }

  // Game state
  const [currentRound, setCurrentRound] = useState(0);
  const [userResponse, setUserResponse] = useState("");
  const [roundScores, setRoundScores] = useState([]);
  const [roundFeedback, setRoundFeedback] = useState(null);
  const [loading, setLoading] = useState(false);

  // Mode 2 dialogue state
  const [dialogueHistory, setDialogueHistory] = useState([]); // [{role, content}]
  const [exchangeCount, setExchangeCount] = useState(0);
  const [currentObjection, setCurrentObjection] = useState("");
  const [dialogueFeedback, setDialogueFeedback] = useState(null);

  // Timer state
  const [timeLeft, setTimeLeft] = useState(60);
  const [timerActive, setTimerActive] = useState(false);
  const timerRef = useRef(null);

  // Streak state
  const [currentStreak, setCurrentStreak] = useState(() => { try { return parseInt(localStorage.getItem("col_streak") || "0"); } catch { return 0; } });
  const [bestStreak, setBestStreak] = useState(() => { try { return parseInt(localStorage.getItem("col_best_streak") || "0"); } catch { return 0; } });
  const [streakMode, setStreakMode] = useState(null); // null | 1 | 2 (which mode they chose in streak)

  // Leaderboard
  const [leaderboard, setLeaderboard] = useState([]);
  const [weeklyGames, setWeeklyGames] = useState(0);
  const [showLeaderboardScreen, setShowLeaderboardScreen] = useState(false);

  const textareaRef = useRef(null);

  const rounds = selectedMode === 2 ? MODE2_ROUNDS : MODE1_ROUNDS;
  const totalRounds = selectedMode === 2 ? 3 : 5;
  // Timer: Speed Close = 60s, Close or Lose + Streak = 120s
  const timerDuration = selectedMode === 1 ? 60 : 120;
  const currentRoundData = rounds[currentRound];
  const totalScore = roundScores.length ? Math.round(roundScores.reduce((a, b) => a + b, 0) / roundScores.length) : 0;
  const topScore = leaderboard[0]?.score || 94;
  const totalPlayers = weeklyGames + Math.min(SEED_USERS_DAILY.length, Math.max(0, 50 - weeklyGames));
  const myRank = leaderboard.findIndex(e => e.isMe) + 1;
  const topPct = myRank > 0 ? Math.max(1, Math.round((myRank / leaderboard.length) * 100)) : null;

  const handleProfileSave = (p) => { localStorage.setItem("col_profile", JSON.stringify(p)); setProfile(p); };
  const [editingProfile, setEditingProfile] = useState(false);

  // Timer
  useEffect(() => {
    if (timerActive && screen === "playing") {
      timerRef.current = setInterval(() => {
        setTimeLeft(t => {
          if (t <= 1) {
            clearInterval(timerRef.current);
            setTimerActive(false);
            handleTimeout();
            return 0;
          }
          return t - 1;
        });
      }, 1000);
    }
    return () => clearInterval(timerRef.current);
  }, [timerActive, screen]);

  const startTimer = () => { setTimeLeft(timerDuration); setTimerActive(true); };
  const stopTimer = () => { clearInterval(timerRef.current); setTimerActive(false); };

  const handleTimeout = async () => {
    const timeout = { overallScore: 0, relevance: 0, salesControl: 0, objectionHandling: 0, confidence: 0, progressToClose: 0, verdict: "Time expired — Deal Lost.", topStrength: "You stayed in the game", topWeakness: "Response speed needs work", coachNote: "In live sales, hesitation kills deals. Practice responding faster — buyers lose confidence when you pause too long." };
    const newScores = [...roundScores, 0];
    setRoundFeedback(timeout);
    setRoundScores(newScores);
    setScreen("scoring");
    if (selectedMode === 3) handleStreakResult(false);
    const isLastRound = currentRound >= totalRounds - 1;
    if (isLastRound) { await submitScore(newScores); await loadLeaderboard(); }
  };

  const loadLeaderboard = async () => {
    const weekStart = getGameWeekStart();
    try {
      const res = await fetch(`${SUPABASE_URL}/rest/v1/col_scores?week_start=eq.${weekStart}&order=score.desc&limit=50`, { headers: { "apikey": SUPABASE_ANON_KEY, "Authorization": `Bearer ${SUPABASE_ANON_KEY}` } });
      const real = res.ok ? await res.json() : [];
      setWeeklyGames(real.length);
      const seedsNeeded = Math.max(0, 50 - real.length);
      const seeds = SEED_USERS_DAILY.slice(0, seedsNeeded).map(s => ({ ...s, isSeed: true }));
      const combined = [
        ...real.map(r => ({ name: r.player_name, title: r.job_title, location: r.location, score: r.score, game_mode: r.game_mode, isSeed: false, isMe: r.user_id === currentUser?.id })),
        ...seeds,
      ].sort((a, b) => b.score - a.score).slice(0, 50);
      setLeaderboard(combined);
    } catch { setLeaderboard(SEED_USERS_DAILY.map(s => ({ ...s, isSeed: true }))); }
  };

  useEffect(() => { loadLeaderboard(); }, []);

  const submitScore = async (scores) => {
    if (!currentUser || !profile) return;
    const finalScore = Math.round(scores.reduce((a, b) => a + b, 0) / scores.length);
    const wins = scores.filter(s => s >= 70).length;
    try {
      await fetch(`${SUPABASE_URL}/rest/v1/col_scores`, {
        method: "POST",
        headers: { "apikey": SUPABASE_ANON_KEY, "Authorization": `Bearer ${SUPABASE_ANON_KEY}`, "Content-Type": "application/json", "Prefer": "resolution=merge-duplicates" },
        body: JSON.stringify({ user_id: currentUser.id, week_start: getGameWeekStart(), player_name: profile.name, job_title: profile.title, location: profile.location, score: finalScore, scenarios_completed: totalRounds, win_rate: Math.round((wins / totalRounds) * 100), game_mode: selectedMode, updated_at: new Date().toISOString() })
      });
    } catch {}
  };

  const handleStreakResult = (won) => {
    if (won) {
      const newStreak = currentStreak + 1;
      setCurrentStreak(newStreak);
      localStorage.setItem("col_streak", String(newStreak));
      if (newStreak > bestStreak) {
        setBestStreak(newStreak);
        localStorage.setItem("col_best_streak", String(newStreak));
      }
    } else {
      setCurrentStreak(0);
      localStorage.setItem("col_streak", "0");
    }
  };

  // ── Mode 1 scoring
  const scoreRoundMode1 = async () => {
    if (!userResponse.trim() || loading) return;
    // Enforce minimum meaningful response length
    if (userResponse.trim().length < 30) {
      setRoundFeedback({ overallScore: 10, relevance: 10, salesControl: 10, objectionHandling: 10, confidence: 10, progressToClose: 10, verdict: "Too short to score. A real buyer would have walked.", topStrength: "You responded", topWeakness: "One sentence doesn't close deals", coachNote: "Buyers expect a real response. Give them something specific — acknowledge what they said, reframe the value, and ask for the next step. At least 2-3 sentences." });
      setRoundScores(prev => [...prev, 10]);
      setScreen("scoring");
      if (selectedMode === 3) handleStreakResult(false);
      const isLast = currentRound >= totalRounds - 1;
      if (isLast) { await submitScore([...roundScores, 10]); await loadLeaderboard(); }
      return;
    }
    stopTimer();
    setLoading(true);
    const r = currentRoundData;
    const objection = currentObjection || (setupConfig ? getPersonalizedObjection(r.objection, setupConfig.industry, setupConfig.personality) : r.objection);
    const industryLabel = COL_INDUSTRIES.find(i => i.id === setupConfig?.industry)?.label || "general sales";
    const roleLabel = COL_ROLES.find(r => r.id === setupConfig?.role)?.label || "Sales Rep";
    const personalityLabel = COL_PERSONALITIES.find(p => p.id === setupConfig?.personality)?.label || "Standard";

    // Per-round difficulty context — escalates across the 5 rounds
    const roundDiffMap = [
      { label: "Round 1 — Warm-Up",    threshold: 65, pressure: "This is Round 1. Be honest but not brutal. A decent response should pass. Generic filler still fails, but a solid attempt earns it." },
      { label: "Round 2 — Building",   threshold: 68, pressure: "Round 2. Raise your standards. The rep should be finding their rhythm. Mediocre reframes no longer pass." },
      { label: "Round 3 — Mid-Point",  threshold: 70, pressure: "Round 3. This is the midpoint. Only responses that specifically address the objection, show real value understanding, AND guide toward a next step score 70+." },
      { label: "Round 4 — Pressure",   threshold: 72, pressure: "Round 4. High pressure. A score of 70+ requires the rep to handle the objection precisely, reframe with specificity, AND attempt a confident close. Generic language = deal lost." },
      { label: "Boss Round — Final",   threshold: 75, pressure: "This is the BOSS ROUND. Be brutally honest. Only an elite response handles all layers and earns 70+. A response that handles 2 of 3 objection layers scores 50-65 max. Vague or partial? 20-45." },
    ];
    const roundCtx = roundDiffMap[Math.min(currentRound, 4)];
    // Streak mode: add extra pressure based on current streak length
    const streakPressure = selectedMode === 3 && currentStreak >= 3
      ? `The rep is on a ${currentStreak}-game streak. Hold them to a higher standard — streak reps get complacent. Be especially critical of any response that feels like a formula.`
      : "";

    const prompt = `You are a strict sales coach scoring a rep in the "Speed Close" game (Mode 1).
Industry: ${industryLabel} | Role: ${roleLabel} | Buyer Personality: ${personalityLabel}
${roundCtx.label} of 5 — Difficulty: "${r.difficulty}"
Objection: "${objection}"
Rep's response: "${userResponse}"

ROUND CONTEXT: ${roundCtx.pressure}
${streakPressure}

UNIVERSAL SCORING RULES — NEVER BREAK THESE:
- Generic, vague, or filler responses ("I understand", "great question", "we can help", "I hear you") MUST score 20-40. No exceptions.
- Responses under 2 meaningful sentences: score 15-35.
- A response that only restates the problem without reframing or advancing: 30-50.
- 70+ threshold for this round: ${roundCtx.threshold}. A score of 70+ means the rep CLOSED THE DEAL.
- The overallScore must equal the mathematical average of the five metric scores.
- coachNote must be specific: quote the rep's actual words and explain exactly what worked or failed. No generic praise.

Score on FIVE weighted metrics (0-100 each). Respond ONLY in this exact JSON (no markdown, no preamble):
{"overallScore":85,"relevance":85,"salesControl":80,"objectionHandling":88,"confidence":82,"progressToClose":80,"verdict":"One sentence verdict.","topStrength":"Specific thing they did well","topWeakness":"Specific thing to improve","coachNote":"Blunt, specific coaching note quoting their actual language."}`;
    try {
      const res = await fetch("https://nahextkqnsmluuskjxps.supabase.co/functions/v1/anthropic-proxy", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${SUPABASE_ANON_KEY}` }, body: JSON.stringify({ model: "claude-sonnet-4-6", max_tokens: 400, messages: [{ role: "user", content: prompt }] }) });
      const data = await res.json();
      const text = (data.content || []).map(c => c.text || "").join("").replace(/```json|```/g, "").trim();
      const parsed = JSON.parse(text);
      const newScores = [...roundScores, parsed.overallScore];
      setRoundFeedback(parsed);
      setRoundScores(newScores);
      setScreen("scoring");
      const won = parsed.overallScore >= 70;
      if (selectedMode === 3) handleStreakResult(won);
      const isLast = currentRound >= totalRounds - 1;
      if (isLast) { await submitScore(newScores); await loadLeaderboard(); }
    } catch {
      const fb = { overallScore: 15, relevance: 10, salesControl: 15, objectionHandling: 15, confidence: 12, progressToClose: 10, verdict: "Scoring failed — response couldn't be evaluated.", topStrength: "You responded", topWeakness: "Response wasn't specific enough to score", coachNote: "Something went wrong scoring your response. Make sure your answer directly addresses the objection, reframes the value, and asks for a commitment." };
      const newScores = [...roundScores, 15];
      setRoundFeedback(fb);
      setRoundScores(newScores);
      setScreen("scoring");
      if (selectedMode === 3) handleStreakResult(false);
      const isLast = currentRound >= totalRounds - 1;
      if (isLast) { await submitScore(newScores); await loadLeaderboard(); }
    }
    setLoading(false);
  };

  // ── Mode 2 — start a round (set opening objection)
  const startMode2Round = () => {
    const r = currentRoundData;
    const objection = setupConfig ? getPersonalizedObjection(r.openingObjection, setupConfig.industry, setupConfig.personality) : r.openingObjection;
    setCurrentObjection(objection);
    setDialogueHistory([{ role: "buyer", content: objection }]);
    setExchangeCount(0);
    setDialogueFeedback(null);
    setScreen("playing");
    startTimer();
  };

  // ── Mode 2 — submit a dialogue exchange
  const submitDialogueResponse = async () => {
    if (!userResponse.trim() || loading) return;
    stopTimer();
    setLoading(true);
    const r = currentRoundData;
    const newHistory = [...dialogueHistory, { role: "rep", content: userResponse }];
    setDialogueHistory(newHistory);
    setUserResponse("");

    const newExchangeCount = exchangeCount + 1;
    setExchangeCount(newExchangeCount);
    const isFinalExchange = newExchangeCount >= r.maxExchanges;

    const industryLabel = COL_INDUSTRIES.find(i => i.id === setupConfig?.industry)?.label || "general sales";
    const personalityLabel = COL_PERSONALITIES.find(p => p.id === setupConfig?.personality)?.label || "Standard";

    if (isFinalExchange) {
      // Score the full dialogue
      const historyText = newHistory.map(m => `${m.role === "buyer" ? "Buyer" : "Rep"}: ${m.content}`).join("\n");
      const mode2RoundCtx = [
        { label: "Round 1 — Discovery Resistance", threshold: 65, pressure: "Round 1. The rep needs to establish curiosity and open the buyer up. A decent attempt earns it. Generic openers still fail." },
        { label: "Round 2 — Objection Battle",     threshold: 70, pressure: "Round 2. The rep should be showing real value-positioning skills now. Reframes must be specific. Blanket statements score 30-50." },
        { label: "Round 3 — Boss Round",           threshold: 75, pressure: "BOSS ROUND. Multi-layered situation requiring confidence, specificity, and a real close. Be brutal. Only elite dialogue earns 70+. Partial handling = 45-65 max." },
      ][Math.min(currentRound, 2)];
      const streakBonus = selectedMode === 3 && currentStreak >= 3
        ? `Rep is on a ${currentStreak}-game streak — apply extra scrutiny. Don't reward formula responses.`
        : "";
      const prompt = `You are a strict sales coach scoring a full sales dialogue in the "Close or Lose" game (Mode 2).
Industry: ${industryLabel} | Buyer: ${personalityLabel} | ${mode2RoundCtx.label}
Full conversation:
${historyText}

ROUND CONTEXT: ${mode2RoundCtx.pressure}
${streakBonus}

SCORING RULES:
- Generic, vague, or non-committal rep responses throughout the conversation MUST result in an overallScore of 20-45.
- If the rep failed to handle objections specifically, reframe value, or ask for commitment: 30-55.
- 70+ threshold this round: ${mode2RoundCtx.threshold}. Requires the rep to have consistently addressed objections, reframed, and guided toward a real close.
- The overallScore must equal the mathematical average of the five metric scores.
- coachNote must reference specific exchanges in the conversation — quote actual lines. No vague feedback.

Score on five metrics (0-100 each). Respond ONLY in this exact JSON (no markdown):
{"overallScore":80,"relevance":78,"salesControl":82,"objectionHandling":80,"confidence":79,"progressToClose":81,"verdict":"One sentence verdict.","topStrength":"Specific strength from the dialogue","topWeakness":"Specific weakness from the dialogue","coachNote":"Blunt coaching note citing specific exchanges."}`;
      try {
        const res = await fetch("https://nahextkqnsmluuskjxps.supabase.co/functions/v1/anthropic-proxy", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${SUPABASE_ANON_KEY}` }, body: JSON.stringify({ model: "claude-sonnet-4-6", max_tokens: 500, messages: [{ role: "user", content: prompt }] }) });
        const data = await res.json();
        const text = (data.content || []).map(c => c.text || "").join("").replace(/```json|```/g, "").trim();
        const parsed = JSON.parse(text);
        const newScores = [...roundScores, parsed.overallScore];
        setRoundFeedback(parsed);
        setRoundScores(newScores);
        setScreen("scoring");
        const won = parsed.overallScore >= 70;
        if (selectedMode === 3) handleStreakResult(won);
        const isLast = currentRound >= totalRounds - 1;
        if (isLast) { await submitScore(newScores); await loadLeaderboard(); }
      } catch {
        const fb = { overallScore: 15, relevance: 12, salesControl: 15, objectionHandling: 14, confidence: 13, progressToClose: 10, verdict: "Scoring failed — dialogue couldn't be evaluated.", topStrength: "You stayed in the conversation", topWeakness: "Responses didn't build enough momentum to score", coachNote: "Something went wrong evaluating this dialogue. In a real multi-turn close, every exchange must move the buyer forward — address each objection specifically and push for commitment." };
        const newScores = [...roundScores, 15];
        setRoundFeedback(fb);
        setRoundScores(newScores);
        setScreen("scoring");
        const isLast = currentRound >= totalRounds - 1;
        if (isLast) { await submitScore(newScores); await loadLeaderboard(); }
      }
    } else {
      // Get buyer's next response — AI-generated, reactive to what the rep actually said
      const historyText = newHistory.map(m => `${m.role === "buyer" ? "Buyer" : "Rep"}: ${m.content}`).join("\n");
      const personalityLabel = COL_PERSONALITIES.find(p => p.id === setupConfig?.personality)?.label || "Skeptical";
      const industryLabel = COL_INDUSTRIES.find(i => i.id === setupConfig?.industry)?.label || "general sales";
      const buyerIntensity = currentRound === 0
        ? "You are resistant but not hostile. You've heard pitches before and you're skeptical. You need a real reason to engage."
        : currentRound === 1
        ? "You are tough and price-focused. You've been burned by vendors before. A weak answer gets a harder counter. A strong answer gets acknowledgment — but one more hard condition."
        : "You are the BOSS ROUND buyer. You are experienced, skeptical, and in control of this conversation. Weak answers get shut down with a harder objection. Strong answers get acknowledged with one final high-stakes condition. You do NOT cave easily.";
      const exchangePressure = newExchangeCount >= r.maxExchanges - 1
        ? "This is the FINAL exchange. If the rep gave a truly compelling close with a specific ask for commitment, you may cautiously signal openness — but state one final condition. If they were weak, shut it down definitively."
        : newExchangeCount >= Math.floor(r.maxExchanges / 2)
        ? "You're halfway through this conversation. Raise your resistance level — ask a harder question or surface a new concern the rep hasn't addressed."
        : "Early in the conversation. You are resistant. A generic opener gets a harder objection. A good one gets a skeptical question.";
      const streakBuyerNote = selectedMode === 3 && currentStreak >= 3
        ? ` The rep is on a ${currentStreak}-game streak. They may be getting formulaic. Be especially hard on responses that feel scripted.`
        : "";
      const buyerPrompt = `You are a ${personalityLabel} buyer in a ${industryLabel} sales conversation.
${buyerIntensity}${streakBuyerNote}

Conversation so far:
${historyText}

Your role in this exchange: ${exchangePressure}

Respond as this buyer. Hard rules:
- Generic rep response ("I understand", "great question", "we can definitely help") → escalate immediately. Add a sharper, more specific objection. Show frustration.
- Somewhat specific but incomplete rep response → acknowledge minimally, then surface a harder follow-on concern.
- Strong, specific, confident rep response with real reasoning → acknowledge it briefly but still press with one realistic concern or harder question.
- Never make it easy. A rep who handles this well still has to work for it.
- Sound like a real human. 1-3 sentences max. No "Buyer:" prefix.`;
      try {
        const res = await fetch("https://nahextkqnsmluuskjxps.supabase.co/functions/v1/anthropic-proxy", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${SUPABASE_ANON_KEY}` }, body: JSON.stringify({ model: "claude-sonnet-4-6", max_tokens: 150, messages: [{ role: "user", content: buyerPrompt }] }) });
        const data = await res.json();
        const buyerReply = (data.content || []).map(c => c.text || "").join("").trim();
        if (buyerReply && buyerReply.length > 5) {
          const nextHistory = [...newHistory, { role: "buyer", content: buyerReply }];
          setDialogueHistory(nextHistory);
          setCurrentObjection(buyerReply);
        } else {
          throw new Error("Empty buyer reply");
        }
      } catch {
        // Fallback to static follow-up if AI call fails or returns empty
        // Pick randomly from the pool so it never feels like a predictable queue
        const followUpPool = r.followUps;
        const followUp = followUpPool[Math.floor(Math.random() * followUpPool.length)];
        const personalizedFollowUp = setupConfig ? getPersonalizedObjection(followUp, setupConfig.industry, setupConfig.personality) : followUp;
        const nextHistory = [...newHistory, { role: "buyer", content: personalizedFollowUp }];
        setDialogueHistory(nextHistory);
        setCurrentObjection(personalizedFollowUp);
      }
      startTimer();
    }
    setLoading(false);
  };

  const nextRound = () => {
    if (currentRound < totalRounds - 1) {
      const nextRoundIndex = currentRound + 1;
      setCurrentRound(nextRoundIndex);
      setUserResponse("");
      setRoundFeedback(null);
      setDialogueHistory([]);
      setExchangeCount(0);
      if (selectedMode === 2) {
        startMode2Round();
      } else {
        // Set the next round's objection in state once so it never re-randomizes
        const r = MODE1_ROUNDS[nextRoundIndex];
        const obj = getPersonalizedObjection(r.objection, setupConfig?.industry, setupConfig?.personality);
        setCurrentObjection(obj);
        setScreen("playing");
        startTimer();
      }
    } else {
      setScreen("scorecard");
    }
  };

  const startGame = (config) => {
    setSetupConfig(config);
    setCurrentRound(0);
    setRoundScores([]);
    setRoundFeedback(null);
    setUserResponse("");
    setDialogueHistory([]);
    setExchangeCount(0);
    if (selectedMode === 2) {
      setScreen("playing");
      const r = MODE2_ROUNDS[0];
      const obj = getPersonalizedObjection(r.openingObjection, config.industry, config.personality);
      setCurrentObjection(obj);
      setDialogueHistory([{ role: "buyer", content: obj }]);
      startTimer();
    } else {
      // Set Mode 1 objection once in state so it doesn't re-randomize on every render
      const r = selectedMode === 3 && streakMode === 2 ? MODE2_ROUNDS[0] : MODE1_ROUNDS[0];
      const obj = getPersonalizedObjection(r.objection || r.openingObjection, config.industry, config.personality);
      setCurrentObjection(obj);
      setScreen("playing");
      startTimer();
    }
  };

  const resetGame = () => {
    setScreen("modeSelect");
    setSelectedMode(null);
    setSetupConfig(null);
    setCurrentRound(0);
    setRoundScores([]);
    setRoundFeedback(null);
    setUserResponse("");
    setDialogueHistory([]);
    setExchangeCount(0);
    stopTimer();
  };

  const handleModeSelect = (modeId) => {
    if (modeId === 3) {
      // Streak mode — pick sub-mode first
      setSelectedMode(3);
      setScreen("streakModeSelect");
    } else {
      setSelectedMode(modeId);
      setScreen("setup");
    }
  };

  if (!profile) return <GameProfileModal onSave={handleProfileSave} onCancel={onExit} />;

  // ── LEADERBOARD SCREEN
  if (showLeaderboardScreen) return (
    <div style={{ position: "fixed", inset: 0, zIndex: 150, background: "#f8fafc", display: "flex", flexDirection: "column", fontFamily: "'Inter', sans-serif" }}>
      <div style={{ paddingTop: "env(safe-area-inset-top)", paddingLeft: 24, paddingRight: 24, paddingBottom: 12, borderBottom: "1px solid #e2e8f0", background: "#ffffff", display: "flex", alignItems: "center", justifyContent: "space-between", flexShrink: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ fontSize: 16 }}>🏆</span>
          <span style={{ fontSize: 13, fontWeight: 700, color: "#0f172a" }}>Weekly Leaderboard</span>
          <span style={{ fontSize: 10, color: "#64748b", background: "#f8fafc", border: "1px solid #e2e8f0", borderRadius: 4, padding: "2px 8px" }}>Resets {getNextSundayReset()}</span>
        </div>
        <button onClick={() => setShowLeaderboardScreen(false)} style={{ background: "transparent", border: "1px solid #e2e8f0", color: "#94a3b8", borderRadius: 6, padding: "5px 14px", fontSize: 11, cursor: "pointer" }}>← Back</button>
      </div>
      <div style={{ flex: 1, overflowY: "auto", padding: "20px 24px" }}>
        <div style={{ maxWidth: 540, margin: "0 auto" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginBottom: 20 }}>
            {[
              { label: "Top Score",        val: leaderboard[0]?.score || "—", color: "#16a34a" },
              { label: "Players This Week", val: `${totalPlayers}+`,           color: "#2563eb" },
              { label: "Your Rank",         val: myRank > 0 ? `#${myRank}` : "—", color: "#16a34a" },
            ].map((s, i) => (
              <div key={i} style={{ padding: "14px", borderRadius: 10, background: "#ffffff", border: "1px solid #e2e8f0", textAlign: "center" }}>
                <div style={{ fontSize: 20, fontWeight: 800, color: s.color, marginBottom: 4 }}>{s.val}</div>
                <div style={{ fontSize: 10, color: "#94a3b8", fontWeight: 600 }}>{s.label}</div>
              </div>
            ))}
          </div>
          {leaderboard.map((entry, i) => {
            const medals = ["🥇", "🥈", "🥉"];
            const scoreColor = i < 3 ? "#16a34a" : "#0f172a";
            const modeMap = { 1: "⚡ Speed Close", 2: "⚔️ Close or Lose", 3: "🔥 Streak" };
            const timerMap = { 1: "60s", 2: "2min", 3: "2min" };
            const entryMode = modeMap[entry.game_mode] || "⚡ Speed Close";
            const entryTimer = timerMap[entry.game_mode] || "60s";
            return (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", borderRadius: 10, background: entry.isMe ? "#f0fdf4" : "#ffffff", border: `1px solid ${entry.isMe ? "#bbf7d0" : "#e2e8f0"}`, marginBottom: 5, opacity: entry.isSeed ? 0.7 : 1 }}>
                <div style={{ width: 22, textAlign: "center", fontSize: i < 3 ? 15 : 11, fontWeight: 700, color: "#94a3b8", flexShrink: 0 }}>{i < 3 ? medals[i] : `#${i + 1}`}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: entry.isMe ? "#16a34a" : "#0f172a", display: "flex", alignItems: "center", gap: 6 }}>
                    {entry.name}
                    {entry.isMe && <span style={{ fontSize: 9, background: "#f0fdf4", color: "#16a34a", border: "1px solid #bbf7d0", borderRadius: 3, padding: "1px 5px", fontWeight: 700 }}>YOU</span>}
                  </div>
                  <div style={{ fontSize: 10, color: "#94a3b8", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{entry.title} · {entry.location}</div>
                </div>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 3, flexShrink: 0 }}>
                  <div style={{ fontSize: 17, fontWeight: 800, color: scoreColor }}>{entry.score}</div>
                  <div style={{ display: "flex", gap: 3 }}>
                    <span style={{ fontSize: 9, fontWeight: 600, padding: "1px 7px", borderRadius: 10, background: "#f1f5f9", color: "#334155", border: "1px solid #e2e8f0" }}>{entryMode}</span>
                    <span style={{ fontSize: 9, fontWeight: 600, padding: "1px 7px", borderRadius: 10, background: "#f1f5f9", color: "#334155", border: "1px solid #e2e8f0" }}>{entryTimer}</span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );

  // ── MODE SELECT
  if (screen === "modeSelect") return (
    <ModeSelectScreen
      onSelect={handleModeSelect}
      onExit={onExit}
      topScore={topScore}
      totalPlayers={totalPlayers}
      isPro={isPro}
      onViewLeaderboard={() => setShowLeaderboardScreen(true)}
    />
  );

  // ── STREAK MODE — PICK SUB-MODE
  if (screen === "streakModeSelect") return (
    <div style={{ position: "fixed", inset: 0, zIndex: 150, background: "#f1f5f9", display: "flex", flexDirection: "column", fontFamily: "'Inter', sans-serif" }}>
      <div style={{ paddingTop: "env(safe-area-inset-top)", paddingLeft: 24, paddingRight: 24, paddingBottom: 14, borderBottom: "1px solid #e2e8f0", background: "#fff", display: "flex", alignItems: "center", justifyContent: "space-between", flexShrink: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: "#0f172a" }}>🔥 Streak Mode — Choose Format</div>
        <button onClick={() => setScreen("modeSelect")} style={{ background: "transparent", border: "1px solid #e2e8f0", color: "#94a3b8", borderRadius: 6, padding: "5px 12px", fontSize: 11, cursor: "pointer" }}>← Back</button>
      </div>
      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
        <div style={{ maxWidth: 440, width: "100%", textAlign: "center" }}>
          {/* Streak display */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginBottom: 28 }}>
            {[{ label: "CURRENT STREAK", val: currentStreak, color: "#ef4444" }, { label: "BEST STREAK", val: bestStreak, color: "#f97316" }, { label: "GLOBAL RANK", val: myRank > 0 ? `Top ${topPct}%` : "—", color: "#3b82f6" }].map((s, i) => (
              <div key={i} style={{ padding: "14px 8px", borderRadius: 10, background: "#fff", border: "1px solid #e2e8f0", textAlign: "center" }}>
                <div style={{ fontSize: i === 0 ? 28 : 20, fontWeight: 800, color: s.color, marginBottom: 4 }}>{s.val}</div>
                <div style={{ fontSize: 8, color: "#94a3b8", fontWeight: 700, letterSpacing: "0.1em" }}>{s.label}</div>
              </div>
            ))}
          </div>
          <div style={{ fontSize: 12, color: "#64748b", marginBottom: 20 }}>Win deals back-to-back. One loss resets your streak to zero.</div>
          {[{ id: 1, label: "⚡ Speed Close", desc: "Fast 5-round objection battles" }, { id: 2, label: "⚔️ Close or Lose", desc: "Full multi-turn deal simulations" }].map(m => (
            <button key={m.id} onClick={() => { setStreakMode(m.id); setSelectedMode(3); setScreen("setup"); }} style={{ width: "100%", marginBottom: 10, padding: "16px 20px", borderRadius: 12, background: "#fff", border: "1.5px solid #e2e8f0", cursor: "pointer", textAlign: "left", fontFamily: "'Inter', sans-serif" }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a", marginBottom: 2 }}>{m.label}</div>
              <div style={{ fontSize: 12, color: "#64748b" }}>{m.desc}</div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );

  // ── SETUP
  if (screen === "setup") return (
    <GameSetupScreen
      mode={selectedMode}
      onStart={startGame}
      onBack={() => setScreen(selectedMode === 3 ? "streakModeSelect" : "modeSelect")}
    />
  );

  // ── PLAYING — shared header
  const PlayingHeader = () => {
    const modeLabel = selectedMode === 1 ? "⚡ Speed Close" : selectedMode === 2 ? "⚔️ Close or Lose" : `🔥 Streak ×${currentStreak}`;
    const timerLabel = selectedMode === 1 ? "60s" : "2min";
    const rData = currentRoundData;
    const pct = timeLeft / timerDuration;
    const radius = 20;
    const circ = 2 * Math.PI * radius;
    const dash = pct * circ;
    const isWarning = timeLeft <= timerDuration * 0.25 && timeLeft > timerDuration * 0.1;
    const isCritical = timeLeft <= timerDuration * 0.1;
    const ringColor = isCritical ? "#ef4444" : isWarning ? "#f59e0b" : "#22c55e";
    const ringBg = isCritical ? "#fef2f2" : isWarning ? "#fffbeb" : "#f0fdf4";
    const textColor = isCritical ? "#dc2626" : isWarning ? "#d97706" : "#16a34a";
    const displayTime = timerDuration >= 120
      ? `${Math.floor(timeLeft / 60)}:${String(timeLeft % 60).padStart(2, "0")}`
      : String(timeLeft);
    return (
      <div style={{ paddingTop: "env(safe-area-inset-top)", paddingLeft: 20, paddingRight: 20, paddingBottom: 10, borderBottom: "1px solid #e2e8f0", background: "#ffffff", display: "flex", alignItems: "center", justifyContent: "space-between", flexShrink: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ fontSize: 12, fontWeight: 700, color: "#0f172a" }}>{modeLabel}</span>
          <span style={{ fontSize: 9, fontWeight: 600, color: "#475569", background: "#f1f5f9", border: "1px solid #e2e8f0", borderRadius: 20, padding: "1px 7px" }}>{timerLabel}</span>
        </div>
        <div style={{ display: "flex", gap: 4, alignItems: "center" }}>
          {Array.from({ length: totalRounds }).map((_, i) => (
            <div key={i} style={{ width: 22, height: 4, borderRadius: 2, background: i < currentRound ? "#22c55e" : i === currentRound ? rData.diffColor : "#e2e8f0" }} />
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {/* SVG ring timer */}
          <div style={{ position: "relative", width: 48, height: 48, flexShrink: 0 }}>
            <svg width="48" height="48" viewBox="0 0 48 48">
              <circle cx="24" cy="24" r={radius} fill={isCritical ? "#fef2f2" : "none"} stroke="#e2e8f0" strokeWidth="4"/>
              <circle cx="24" cy="24" r={radius} fill="none" stroke={ringColor} strokeWidth="4"
                strokeDasharray={`${dash} ${circ}`} strokeLinecap="round"
                transform="rotate(-90 24 24)" style={{ transition: "stroke-dasharray 0.9s linear, stroke 0.3s" }}/>
            </svg>
            <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
              <span style={{ fontSize: timerDuration >= 120 ? 10 : 13, fontWeight: 800, color: textColor, lineHeight: 1 }}>{displayTime}</span>
            </div>
          </div>
          {/* Color-coded time label badge */}
          <div style={{ fontSize: 10, fontWeight: 700, color: textColor, background: ringBg, border: `1px solid ${ringColor}30`, borderRadius: 20, padding: "3px 9px", minWidth: 38, textAlign: "center", transition: "all 0.3s" }}>{displayTime}</div>
          <button onClick={onExit} style={{ background: "transparent", border: "1px solid #e2e8f0", color: "#94a3b8", borderRadius: 6, padding: "4px 10px", fontSize: 10, cursor: "pointer" }}>Quit</button>
        </div>
      </div>
    );
  };

  // ── PLAYING — MODE 1
  if (screen === "playing" && selectedMode !== 2) {
    const r = currentRoundData;
    const objection = currentObjection || (setupConfig ? getPersonalizedObjection(r.objection, setupConfig.industry, setupConfig.personality) : r.objection);
    const industryLabel = COL_INDUSTRIES.find(i => i.id === setupConfig?.industry)?.label || "";
    return (
      <div style={{ position: "fixed", inset: 0, zIndex: 150, background: "#f1f5f9", display: "flex", flexDirection: "column", fontFamily: "'Inter', sans-serif" }}>
        <PlayingHeader />
        <div style={{ flex: 1, overflowY: "auto", padding: "20px 24px", display: "flex", flexDirection: "column", alignItems: "center" }}>
          <div style={{ maxWidth: 580, width: "100%" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14 }}>
              <span style={{ fontSize: 10, fontWeight: 700, color: r.diffColor, background: `${r.diffColor}15`, border: `1px solid ${r.diffColor}30`, borderRadius: 20, padding: "2px 10px" }}>{r.difficulty}</span>
              <span style={{ fontSize: 10, color: "#94a3b8" }}>{r.label} · Round {currentRound + 1} of {totalRounds}</span>
              {industryLabel && <span style={{ fontSize: 10, color: "#94a3b8" }}>· {industryLabel}</span>}
            </div>
            <div style={{ marginBottom: 16, padding: "14px 16px", borderRadius: 10, background: "#fff", border: "1px solid #e2e8f0" }}>
              <div style={{ fontSize: 9, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.12em", marginBottom: 6 }}>SKILL TESTED</div>
              <div style={{ fontSize: 12, color: "#475569" }}>{r.skillTested}</div>
            </div>
            <div style={{ marginBottom: 16, padding: "16px 18px", borderRadius: 10, background: "#fff", border: `1.5px solid ${r.diffColor}40` }}>
              <div style={{ fontSize: 9, fontWeight: 700, color: r.diffColor, letterSpacing: "0.12em", marginBottom: 8 }}>BUYER SAYS:</div>
              <div style={{ fontSize: 15, fontWeight: 600, color: "#0f172a", lineHeight: 1.7, fontStyle: "italic" }}>"{objection}"</div>
            </div>
            <div style={{ fontSize: 9, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.1em", marginBottom: 8 }}>YOUR RESPONSE — Close it.</div>
            <div style={{ background: "#fff", border: "1.5px solid #e2e8f0", borderRadius: 12, padding: "12px 14px", display: "flex", alignItems: "flex-end", gap: 10 }}>
              <textarea ref={textareaRef} value={userResponse} onChange={e => { setUserResponse(e.target.value); e.target.style.height = "auto"; e.target.style.height = Math.min(e.target.scrollHeight, 140) + "px"; }} onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); scoreRoundMode1(); } }} placeholder="Type your response and close the deal..." rows={3} style={{ flex: 1, background: "transparent", border: "none", color: "#0f172a", fontSize: 13.5, lineHeight: 1.65, fontFamily: "'Inter', sans-serif", resize: "none", outline: "none", maxHeight: 140 }} />
              <button onClick={scoreRoundMode1} disabled={!userResponse.trim() || loading} style={{ width: 38, height: 38, borderRadius: 8, flexShrink: 0, background: userResponse.trim() && !loading ? "#0f172a" : "#f1f5f9", border: "none", color: userResponse.trim() && !loading ? "#fff" : "#94a3b8", fontSize: 15, cursor: userResponse.trim() && !loading ? "pointer" : "not-allowed", display: "flex", alignItems: "center", justifyContent: "center" }}>{loading ? "…" : "↑"}</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ── PLAYING — MODE 2 (dialogue)
  if (screen === "playing" && selectedMode === 2) {
    const r = currentRoundData;
    return (
      <div style={{ position: "fixed", inset: 0, zIndex: 150, background: "#f1f5f9", display: "flex", flexDirection: "column", fontFamily: "'Inter', sans-serif" }}>
        <PlayingHeader />
        <div style={{ flex: 1, overflowY: "auto", padding: "16px 24px", display: "flex", flexDirection: "column", alignItems: "center" }}>
          <div style={{ maxWidth: 580, width: "100%" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14 }}>
              <span style={{ fontSize: 10, fontWeight: 700, color: r.diffColor, background: `${r.diffColor}15`, border: `1px solid ${r.diffColor}30`, borderRadius: 20, padding: "2px 10px" }}>{r.difficulty}</span>
              <span style={{ fontSize: 10, color: "#94a3b8" }}>{r.label} · Round {currentRound + 1} of {totalRounds} · Exchange {exchangeCount + 1}/{r.maxExchanges}</span>
            </div>
            {/* Dialogue history */}
            <div style={{ marginBottom: 14 }}>
              {dialogueHistory.map((msg, i) => (
                <div key={i} style={{ marginBottom: 8, display: "flex", flexDirection: msg.role === "rep" ? "row-reverse" : "row", gap: 8 }}>
                  <div style={{ maxWidth: "78%", padding: "10px 14px", borderRadius: msg.role === "rep" ? "12px 3px 12px 12px" : "3px 12px 12px 12px", background: msg.role === "rep" ? "#0f172a" : "#fff", border: msg.role === "rep" ? "none" : `1.5px solid ${r.diffColor}40`, color: msg.role === "rep" ? "#f1f5f9" : "#0f172a", fontSize: 13, lineHeight: 1.6, fontStyle: msg.role === "buyer" ? "italic" : "normal" }}>
                    {msg.role === "buyer" && <div style={{ fontSize: 9, fontWeight: 700, color: r.diffColor, letterSpacing: "0.1em", marginBottom: 4 }}>BUYER:</div>}
                    {msg.content}
                  </div>
                </div>
              ))}
              {loading && (
                <div style={{ display: "flex", gap: 5, padding: "8px 14px", borderRadius: "3px 12px 12px 12px", background: "#fff", border: "1px solid #e2e8f0", width: "fit-content", marginBottom: 8 }}>
                  {[0,1,2].map(i => <div key={i} style={{ width: 5, height: 5, borderRadius: "50%", background: "#94a3b8", animation: "bounceDot 1.2s infinite", animationDelay: `${i * 0.18}s` }} />)}
                </div>
              )}
            </div>
            {/* Response input */}
            {!loading && (
              <>
                <div style={{ fontSize: 9, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.1em", marginBottom: 6 }}>YOUR RESPONSE:</div>
                <div style={{ background: "#fff", border: "1.5px solid #e2e8f0", borderRadius: 12, padding: "10px 12px", display: "flex", alignItems: "flex-end", gap: 10 }}>
                  <textarea ref={textareaRef} value={userResponse} onChange={e => { setUserResponse(e.target.value); e.target.style.height = "auto"; e.target.style.height = Math.min(e.target.scrollHeight, 120) + "px"; }} onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); submitDialogueResponse(); } }} placeholder={exchangeCount >= r.maxExchanges - 1 ? "Final response — close the deal..." : "Respond to keep the conversation going..."} rows={2} style={{ flex: 1, background: "transparent", border: "none", color: "#0f172a", fontSize: 13, lineHeight: 1.6, fontFamily: "'Inter', sans-serif", resize: "none", outline: "none", maxHeight: 120 }} />
                  <button onClick={submitDialogueResponse} disabled={!userResponse.trim() || loading} style={{ width: 36, height: 36, borderRadius: 8, flexShrink: 0, background: userResponse.trim() ? "#0f172a" : "#f1f5f9", border: "none", color: userResponse.trim() ? "#fff" : "#94a3b8", fontSize: 14, cursor: userResponse.trim() ? "pointer" : "not-allowed", display: "flex", alignItems: "center", justifyContent: "center" }}>↑</button>
                </div>
                {exchangeCount >= r.maxExchanges - 1 && (
                  <div style={{ marginTop: 6, fontSize: 10, color: "#ef4444", fontWeight: 600 }}>⚠️ Final exchange — make your close count.</div>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    );
  }

  // ── SCORING
  if (screen === "scoring" && roundFeedback) {
    const closed = roundFeedback.overallScore >= 70;
    const isLastRound = currentRound >= totalRounds - 1;
    const nextRoundData = !isLastRound ? rounds[currentRound + 1] : null;

    const metrics = [
      { label: "Relevance", key: "relevance", weight: "30%" },
      { label: "Sales Control", key: "salesControl", weight: "20%" },
      { label: "Objection Handling", key: "objectionHandling", weight: "20%" },
      { label: "Confidence", key: "confidence", weight: "15%" },
      { label: "Progress to Close", key: "progressToClose", weight: "15%" },
    ];

    return (
      <div style={{ position: "fixed", inset: 0, zIndex: 150, background: "#f1f5f9", display: "flex", flexDirection: "column", fontFamily: "'Inter', sans-serif" }}>
        <div style={{ paddingTop: "env(safe-area-inset-top)", paddingLeft: 24, paddingRight: 24, paddingBottom: 12, borderBottom: "1px solid #e2e8f0", background: "#ffffff", display: "flex", alignItems: "center", justifyContent: "space-between", flexShrink: 0 }}>
          <span style={{ fontSize: 12, fontWeight: 700, color: "#0f172a" }}>
            {selectedMode === 1 ? "⚡" : "⚔️"} Round {currentRound + 1} Result
          </span>
          <div style={{ display: "flex", gap: 5 }}>
            {Array.from({ length: totalRounds }).map((_, i) => (
              <div key={i} style={{ width: 24, height: 4, borderRadius: 2, background: i < currentRound ? "#22c55e" : i === currentRound ? (closed ? "#22c55e" : "#ef4444") : "#e2e8f0", border: "1px solid #e2e8f0" }} />
            ))}
          </div>
          <div style={{ width: 50 }} />
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: "20px 24px", display: "flex", flexDirection: "column", alignItems: "center" }}>
          <div style={{ maxWidth: 520, width: "100%" }}>
            <div style={{ textAlign: "center", marginBottom: 20 }}>
              <div style={{ fontSize: 40, marginBottom: 6 }}>{closed ? "🏆" : "💀"}</div>
              <div style={{ fontSize: 22, fontWeight: 800, color: closed ? "#16a34a" : "#dc2626", marginBottom: 4 }}>{closed ? "Deal Closed!" : "Deal Lost."}</div>
              <div style={{ fontSize: 13, color: "#64748b", fontStyle: "italic" }}>"{roundFeedback.verdict}"</div>
              {selectedMode === 3 && (
                <div style={{ marginTop: 8, display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 12px", borderRadius: 20, background: closed ? "#f0fdf4" : "#fef2f2", border: `1px solid ${closed ? "#bbf7d0" : "#fecaca"}` }}>
                  <span style={{ fontSize: 11, fontWeight: 700, color: closed ? "#16a34a" : "#dc2626" }}>🔥 Streak: {currentStreak}</span>
                </div>
              )}
            </div>
            {/* Metrics grid */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 14 }}>
              {metrics.map((m, i) => (
                <div key={i} style={{ padding: "12px 14px", borderRadius: 10, background: "#ffffff", border: "1px solid #e2e8f0" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                    <div style={{ fontSize: 10, color: "#64748b", fontWeight: 600 }}>{m.label}</div>
                    <div style={{ fontSize: 9, color: "#94a3b8" }}>{m.weight}</div>
                  </div>
                  <div style={{ height: 3, background: "#f1f5f9", borderRadius: 2, marginBottom: 5 }}>
                    <div style={{ height: "100%", borderRadius: 2, width: `${roundFeedback[m.key] || 0}%`, background: scoreColor(roundFeedback[m.key] || 0).bar }} />
                  </div>
                  <div style={{ fontSize: 17, fontWeight: 800, color: scoreColor(roundFeedback[m.key] || 0).text }}>{roundFeedback[m.key] || 0}</div>
                </div>
              ))}
              <div style={{ padding: "12px 14px", borderRadius: 10, background: scoreColor(roundFeedback.overallScore).bg, border: `1px solid ${scoreColor(roundFeedback.overallScore).border}`, display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}>
                <div style={{ fontSize: 9, color: scoreColor(roundFeedback.overallScore).text, fontWeight: 700, letterSpacing: "0.1em", marginBottom: 4 }}>ROUND SCORE</div>
                <div style={{ fontSize: 28, fontWeight: 800, color: scoreColor(roundFeedback.overallScore).text }}>{roundFeedback.overallScore}</div>
              </div>
            </div>
            {/* Coach */}
            <div style={{ padding: "14px 16px", borderRadius: 10, background: "#fff", border: "1px solid #e2e8f0", marginBottom: 14 }}>
              <div style={{ display: "flex", gap: 14, marginBottom: 10 }}>
                <div style={{ flex: 1 }}><div style={{ fontSize: 9, fontWeight: 700, color: "#16a34a", letterSpacing: "0.1em", marginBottom: 3 }}>💪 STRENGTH</div><div style={{ fontSize: 12, color: "#475569" }}>{roundFeedback.topStrength}</div></div>
                <div style={{ flex: 1 }}><div style={{ fontSize: 9, fontWeight: 700, color: "#d97706", letterSpacing: "0.1em", marginBottom: 3 }}>🎯 IMPROVE</div><div style={{ fontSize: 12, color: "#475569" }}>{roundFeedback.topWeakness}</div></div>
              </div>
              <div style={{ fontSize: 9, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.1em", marginBottom: 5 }}>COACH NOTE</div>
              <div style={{ fontSize: 12, color: "#64748b", lineHeight: 1.7 }}>{roundFeedback.coachNote}</div>
            </div>
            <button onClick={nextRound} style={{ width: "100%", padding: "14px", borderRadius: 10, border: "none", background: "#0f172a", color: "#fff", fontSize: 14, fontWeight: 700, cursor: "pointer" }}>
              {isLastRound ? "See My Scorecard 🏆" : `Round ${currentRound + 2}: ${nextRoundData?.difficulty} →`}
            </button>
          </div>
        </div>
      </div>
    );
  }

  // ── SCORECARD
  if (screen === "scorecard") {
    const wins = roundScores.filter(s => s >= 70).length;
    const winRate = Math.round((wins / totalRounds) * 100);
    const modeLabel = selectedMode === 1 ? "Speed Close" : selectedMode === 2 ? "Close or Lose" : "Streak Mode";
    const modeIcon = selectedMode === 1 ? "⚡" : selectedMode === 2 ? "⚔️" : "🔥";
    const timerLabel = selectedMode === 1 ? "60s" : "2min";
    const industryLabel = COL_INDUSTRIES.find(i => i.id === setupConfig?.industry)?.label || "";
    const roleLabel = COL_ROLES.find(r => r.id === setupConfig?.role)?.label || "";
    const skillLabels = [
      { label: "Sales Control",      score: Math.min(99, Math.round(totalScore * 0.98 + 2)) },
      { label: "Objection Handling", score: totalScore },
      { label: "Confidence",         score: Math.min(99, Math.round(totalScore * 0.97 + 3)) },
      { label: "Relevance",          score: Math.min(99, Math.round(totalScore * 0.96 + 2)) },
      { label: "Progress to Close",  score: Math.min(99, Math.round(totalScore * 0.95)) },
      { label: "Natural Delivery",   score: Math.min(99, Math.round(totalScore * 0.94 + 4)) },
    ];
    const topSkill  = [...skillLabels].sort((a, b) => b.score - a.score)[0];
    const weakSkill = [...skillLabels].sort((a, b) => a.score - b.score)[0];

    return (
      <div style={{ position: "fixed", inset: 0, zIndex: 150, background: "#f8fafc", display: "flex", flexDirection: "column", fontFamily: "'Inter', sans-serif" }}>
        <div style={{ paddingTop: "env(safe-area-inset-top)", paddingLeft: 24, paddingRight: 24, paddingBottom: 12, borderBottom: "1px solid #e2e8f0", background: "#ffffff", display: "flex", alignItems: "center", justifyContent: "space-between", flexShrink: 0 }}>
          <span style={{ fontSize: 13, fontWeight: 700, color: "#0f172a" }}>Your Scorecard</span>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setShowLeaderboardScreen(true)} style={{ background: "transparent", border: "1px solid #e2e8f0", color: "#475569", borderRadius: 6, padding: "5px 14px", fontSize: 11, cursor: "pointer" }}>🏆 Leaderboard</button>
            <button onClick={onExit} style={{ background: "transparent", border: "1px solid #e2e8f0", color: "#94a3b8", borderRadius: 6, padding: "5px 14px", fontSize: 11, cursor: "pointer" }}>Exit</button>
          </div>
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: "20px 24px", display: "flex", flexDirection: "column", alignItems: "center" }}>
          <div style={{ maxWidth: 440, width: "100%" }}>
            <div style={{ padding: "10px 16px", borderRadius: 10, background: scoreColor(totalScore).bg, border: `1px solid ${scoreColor(totalScore).border}`, marginBottom: 16, display: "flex", gap: 10, alignItems: "center", justifyContent: "center" }}>
              <span style={{ fontSize: 18 }}>{totalScore >= 92 ? "🏆" : totalScore >= 75 ? "💪" : totalScore >= 60 ? "📈" : "🎯"}</span>
              <div style={{ fontSize: 13, color: scoreColor(totalScore).text, fontWeight: 700 }}>{scoreColor(totalScore).label} · {totalScore}/100 — share your result below</div>
            </div>

            {/* Scorecard card */}
            <div style={{ background: "#ffffff", border: "1px solid #e2e8f0", borderRadius: 16, overflow: "hidden", boxShadow: "0 4px 24px rgba(15,23,42,0.08)" }}>

              {/* Header */}
              <div style={{ background: "#f8fafc", borderBottom: "1px solid #e2e8f0", padding: "16px 20px" }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <img src={BRAND_CONFIG.logoPath} alt={BRAND_CONFIG.appNameShort} style={{ width: 26, height: 26, borderRadius: 6, objectFit: "cover" }} onError={e => { e.target.style.display = "none"; }} />
                    <div>
                      <div style={{ fontSize: 12, fontWeight: 700, color: "#0f172a" }}>{BRAND_CONFIG.appNameShort}</div>
                      <div style={{ fontSize: 9, color: "#94a3b8", letterSpacing: "0.1em" }}>CLOSE OR LOSE</div>
                    </div>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 4 }}>
                    <span style={{ fontSize: 10, fontWeight: 700, color: "#334155", background: "#f1f5f9", border: "1px solid #e2e8f0", borderRadius: 20, padding: "2px 9px" }}>{modeIcon} {modeLabel}</span>
                    <span style={{ fontSize: 10, fontWeight: 700, color: "#334155", background: "#f1f5f9", border: "1px solid #e2e8f0", borderRadius: 20, padding: "2px 9px" }}>{timerLabel} timer</span>
                    {industryLabel && <span style={{ fontSize: 9, color: "#94a3b8" }}>{industryLabel}{roleLabel ? ` · ${roleLabel}` : ""}</span>}
                  </div>
                </div>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    {profile.photo
                      ? <img src={profile.photo} alt="" style={{ width: 44, height: 44, borderRadius: "50%", objectFit: "cover", border: "2px solid #e2e8f0" }} />
                      : <div style={{ width: 44, height: 44, borderRadius: "50%", background: "#e2e8f0", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 18, color: "#94a3b8" }}>👤</div>
                    }
                    <div>
                      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>{profile.name}</div>
                        <button onClick={() => setEditingProfile(true)} style={{ background: "none", border: "1px solid #e2e8f0", borderRadius: 5, padding: "1px 7px", fontSize: 10, color: "#64748b", cursor: "pointer", fontFamily: "'Inter', sans-serif", fontWeight: 600 }}>Edit</button>
                      </div>
                      <div style={{ fontSize: 11, color: "#64748b" }}>{profile.title}</div>
                      <div style={{ fontSize: 10, color: "#94a3b8" }}>📍 {profile.location}</div>
                    </div>
                  </div>
                  <div style={{ position: "relative", width: 68, height: 68, flexShrink: 0 }}>
                    <svg width="68" height="68" viewBox="0 0 68 68">
                      <circle cx="34" cy="34" r="28" fill="none" stroke="#f1f5f9" strokeWidth="5"/>
                      <circle cx="34" cy="34" r="28" fill="none" stroke={scoreColor(totalScore).bar} strokeWidth="5"
                        strokeDasharray={`${(totalScore / 100) * 176} 176`} strokeLinecap="round" transform="rotate(-90 34 34)"/>
                    </svg>
                    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
                      <div style={{ fontSize: 20, fontWeight: 800, color: scoreColor(totalScore).text, lineHeight: 1 }}>{totalScore}</div>
                      <div style={{ fontSize: 8, color: "#94a3b8" }}>/100</div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Stat bar */}
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", borderBottom: "1px solid #e2e8f0" }}>
                {[
                  { label: "RANK",       val: topPct ? `Top ${topPct}%` : "—",   color: "#16a34a" },
                  { label: "ROUNDS WON", val: `${wins}/${totalRounds}`,           color: wins >= totalRounds * 0.6 ? "#16a34a" : "#dc2626" },
                  { label: "WIN RATE",   val: `${winRate}%`,                      color: winRate >= 60 ? "#16a34a" : "#d97706" },
                  { label: "STREAK",     val: currentStreak,                      color: "#0f172a" },
                ].map((s, i) => (
                  <div key={i} style={{ padding: "11px 6px", textAlign: "center", borderRight: i < 3 ? "1px solid #e2e8f0" : "none", background: i % 2 === 0 ? "#fff" : "#fafbfc" }}>
                    <div style={{ fontSize: 13, fontWeight: 800, color: s.color, marginBottom: 2 }}>{s.val}</div>
                    <div style={{ fontSize: 8, color: "#94a3b8", fontWeight: 700, letterSpacing: "0.08em" }}>{s.label}</div>
                  </div>
                ))}
              </div>

              {/* Skill breakdown */}
              <div style={{ padding: "16px 20px", borderBottom: "1px solid #e2e8f0" }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: "#64748b", letterSpacing: "0.1em", marginBottom: 12 }}>SKILL BREAKDOWN</div>
                {skillLabels.map((s, i) => (
                  <div key={i} style={{ marginBottom: 9 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 3 }}>
                      <span style={{ fontSize: 11, color: "#475569" }}>{s.label}</span>
                      <span style={{ fontSize: 12, fontWeight: 700, color: scoreColor(s.score).text }}>{s.score}</span>
                    </div>
                    <div style={{ height: 4, borderRadius: 4, background: "#f1f5f9", overflow: "hidden" }}>
                      <div style={{ height: "100%", borderRadius: 4, width: `${s.score}%`, background: scoreColor(s.score).bar }} />
                    </div>
                  </div>
                ))}
              </div>

              {/* Insights */}
              <div style={{ padding: "12px 20px", borderBottom: "1px solid #e2e8f0", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                <div style={{ background: "#f0fdf4", border: "1px solid #bbf7d0", borderRadius: 8, padding: "10px 12px" }}>
                  <div style={{ fontSize: 9, fontWeight: 700, color: "#16a34a", letterSpacing: "0.08em", marginBottom: 3 }}>TOP STRENGTH</div>
                  <div style={{ fontSize: 11, fontWeight: 600, color: "#0f172a" }}>{topSkill.label}</div>
                </div>
                <div style={{ background: "#fef2f2", border: "1px solid #fecaca", borderRadius: 8, padding: "10px 12px" }}>
                  <div style={{ fontSize: 9, fontWeight: 700, color: "#dc2626", letterSpacing: "0.08em", marginBottom: 3 }}>FOCUS AREA</div>
                  <div style={{ fontSize: 11, fontWeight: 600, color: "#0f172a" }}>{weakSkill.label}</div>
                </div>
              </div>

              {/* Footer */}
              <div style={{ padding: "10px 20px", background: "#f8fafc", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <div style={{ fontSize: 9, color: "#94a3b8", fontWeight: 600, letterSpacing: "0.1em" }}>{BRAND_CONFIG.appUrl.replace("https://","").toUpperCase()}</div>
                <div style={{ fontSize: 9, color: "#94a3b8" }}>Resets {getNextSundayReset()}</div>
              </div>
            </div>

            {/* Share + Train Again */}
            {(() => {
              const colCopy = (text, label) => {
                if (navigator.clipboard && window.isSecureContext) {
                  navigator.clipboard.writeText(text).catch(() => {});
                } else {
                  try { const ta = document.createElement("textarea"); ta.value = text; ta.style.cssText = "position:fixed;top:-9999px;left:-9999px;"; document.body.appendChild(ta); ta.focus(); ta.select(); document.execCommand("copy"); document.body.removeChild(ta); } catch {}
                }
              };
              const challengeUrl = `https://thesaleslabai.com/challenge?s=${totalScore}&r=${encodeURIComponent(roleLabel || "Sales Rep")}&i=${encodeURIComponent(industryLabel || "Sales")}&m=${encodeURIComponent(modeLabel)}`;
              const liPost = `Just scored ${totalScore}/100 in ${modeIcon} ${modeLabel} on SalesLab AI — ${wins}/${totalRounds} rounds closed.\n\nTop skill: ${topSkill.label}. Focus area: ${weakSkill.label}.\n\nThink you can beat it? Take the challenge:\n${challengeUrl}\n\n#SalesTraining #SalesLab #CloserMindset #SalesPerformance`;
              // LinkedIn share-offsite only supports ?url= — text must be copied separately
              const liShareUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(challengeUrl)}`;
              const [colToast, setColToast] = React.useState("");
              const showColToast = (msg) => { setColToast(msg); setTimeout(() => setColToast(""), 2200); };
              return (
                <div style={{ marginTop: 16 }}>
                  {/* Share nudge */}
                  <div style={{ padding: "12px 16px", borderRadius: 10, background: "#eff6ff", border: "1px solid #bfdbfe", marginBottom: 14, display: "flex", gap: 10, alignItems: "center" }}>
                    <span style={{ fontSize: 16, flexShrink: 0 }}>⚔️</span>
                    <div style={{ fontSize: 12, color: "#1d4ed8", lineHeight: 1.55 }}>
                      <strong>You scored {totalScore}.</strong> Challenge someone to beat it — share your scorecard before you train again.
                    </div>
                  </div>

                  {/* LinkedIn post preview */}
                  <div style={{ background: "#f8fafc", border: "0.5px solid #e2e8f0", borderRadius: 10, padding: 14, marginBottom: 12 }}>
                    <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", color: "#94a3b8", marginBottom: 8 }}>Your LinkedIn post — ready to copy</div>
                    <div style={{ fontSize: 12, color: "#334155", lineHeight: 1.6, whiteSpace: "pre-line", marginBottom: 10 }}>{liPost}</div>
                    <button onClick={() => { colCopy(liPost, ""); showColToast("Post copied!"); }} style={{ width: "100%", padding: "9px", background: "#fff", border: "0.5px solid #d1d9e6", borderRadius: 7, fontSize: 12, fontWeight: 600, color: "#1d4ed8", cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Copy LinkedIn post</button>
                  </div>

                  {/* Challenge link */}
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", background: "#eff6ff", border: "0.5px solid #bfdbfe", borderRadius: 8, padding: "10px 14px", marginBottom: 14 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: "#1d4ed8" }}>Challenge link</div>
                    <div style={{ fontSize: 11, color: "#475569", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 160, marginLeft: 8 }}>{challengeUrl.replace("https://","")}</div>
                    <div onClick={() => { colCopy(challengeUrl, ""); showColToast("Challenge link copied!"); }} style={{ fontSize: 12, fontWeight: 700, color: "#1d4ed8", cursor: "pointer", marginLeft: 8, flexShrink: 0 }}>Copy →</div>
                  </div>

                  {/* LinkedIn tip */}
                  <div style={{ background:"#F0F4FF", border:"0.5px solid #BFDBFE", borderRadius:8, padding:"10px 14px", marginBottom:12, fontSize:12, color:"#1E3A8A", lineHeight:1.5 }}>
                    💡 <strong>LinkedIn tip:</strong> Click "Copy + LinkedIn" — it copies your post text, then opens LinkedIn. Just paste it in.
                  </div>

                  {/* Action buttons */}
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginBottom: 12 }}>
                    {[
                      { icon: "🔗", label: "Copy link",      fn: () => { colCopy(challengeUrl, ""); showColToast("Copied!"); } },
                      { icon: "💼", label: "Copy + LinkedIn", fn: () => { colCopy(liPost, ""); window.open(liShareUrl, "_blank"); showColToast("Post copied! Paste into LinkedIn →"); } },
                      { icon: "📸", label: "Screenshot",     fn: () => showColToast("Screenshot the scorecard above!") },
                    ].map(btn => (
                      <div key={btn.label} onClick={btn.fn} style={{ background: "#fff", border: "0.5px solid #e2e8f0", borderRadius: 8, padding: "10px 8px", textAlign: "center", cursor: "pointer" }}>
                        <div style={{ fontSize: 18, marginBottom: 4 }}>{btn.icon}</div>
                        <div style={{ fontSize: 11, fontWeight: 500, color: "#0f172a" }}>{btn.label}</div>
                      </div>
                    ))}
                  </div>

                  {/* Train Again + Leaderboard */}
                  <div style={{ display: "flex", gap: 8 }}>
                    <button onClick={resetGame} style={{ flex: 1, padding: "13px", borderRadius: 10, border: "none", background: "#0f172a", color: "#fff", fontSize: 13, fontWeight: 700, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Train Again →</button>
                    <button onClick={() => setShowLeaderboardScreen(true)} style={{ padding: "13px 16px", borderRadius: 10, border: "1px solid #e2e8f0", background: "#fff", color: "#475569", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>🏆</button>
                  </div>

                  {colToast && <div style={{ marginTop: 12, textAlign: "center", padding: "8px 16px", background: "#1d4ed8", color: "#fff", borderRadius: 8, fontSize: 12, fontWeight: 500 }}>{colToast}</div>}
                </div>
              );
            })()}
          </div>
        </div>
        {editingProfile && (
          <GameProfileModal
            onSave={(p) => { handleProfileSave(p); setEditingProfile(false); }}
            onCancel={() => setEditingProfile(false)}
            existing={profile}
          />
        )}
      </div>
    );
  }

  return null;
}


// ─── Home Screen Leaderboard Teaser ──────────────────────────────────────────
function HomeLeaderboardTeaser({ onViewLeaderboard }) {
  const [top3, setTop3] = useState([]);

  useEffect(() => {
    const load = async () => {
      const weekStart = getGameWeekStart();
      try {
        const res = await fetch(`${SUPABASE_URL}/rest/v1/col_scores?week_start=eq.${weekStart}&order=score.desc&limit=3`, { headers: { "apikey": SUPABASE_ANON_KEY, "Authorization": `Bearer ${SUPABASE_ANON_KEY}` } });
        const real = res.ok ? await res.json() : [];
        const entries = real.map(r => ({ name: r.player_name, score: r.score, isSeed: false }));
        const needed = Math.max(0, 3 - entries.length);
        const seeds = SEED_USERS_DAILY.slice(0, needed).map(s => ({ name: s.name, score: s.score, isSeed: true }));
        setTop3([...entries, ...seeds].sort((a, b) => b.score - a.score).slice(0, 3));
      } catch {
        setTop3(SEED_USERS_DAILY.slice(0, 3).map(s => ({ name: s.name, score: s.score, isSeed: true })));
      }
    };
    load();
  }, []);

  const medals = ["🥇", "🥈", "🥉"];

  return (
    <div style={{ marginBottom: 20, padding: "14px 16px", borderRadius: 12, background: "#ffffff", border: "0.5px solid #D1D9E6" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
          <span style={{ fontSize: 13 }}>🏆</span>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: "#0f172a" }}>This Week's Top Closers</div>
            <div style={{ fontSize: 10, color: "#94a3b8" }}>Resets {getNextSundayReset()}</div>
          </div>
        </div>
        <button onClick={onViewLeaderboard} style={{ background: "none", border: "none", color: "#64748b", fontSize: 11, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif", padding: 0 }}>
          Full board →
        </button>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        {top3.map((entry, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, opacity: entry.isSeed ? 0.75 : 1 }}>
            <span style={{ fontSize: 14, flexShrink: 0, width: 20 }}>{medals[i]}</span>
            <span style={{ flex: 1, fontSize: 12.5, fontWeight: 600, color: "#0f172a", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", minWidth: 0 }}>{entry.name}</span>
            <span style={{ fontSize: 14, fontWeight: 800, color: i === 0 ? scoreColor(entry.score).text : "#64748b", flexShrink: 0, minWidth: 28, textAlign: "right" }}>{entry.score}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Mini Leaderboard Modal ───────────────────────────────────────────────────
function MiniLeaderboard({ currentUser, onClose, onPlay, isPro }) {
  const [leaderboard, setLeaderboard] = useState([]);
  const [weeklyGames, setWeeklyGames] = useState(0);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const load = async () => {
      const weekStart = getGameWeekStart();
      try {
        const res = await fetch(`${SUPABASE_URL}/rest/v1/col_scores?week_start=eq.${weekStart}&order=score.desc&limit=50`, { headers: { "apikey": SUPABASE_ANON_KEY, "Authorization": `Bearer ${SUPABASE_ANON_KEY}` } });
        const real = res.ok ? await res.json() : [];
        setWeeklyGames(real.length);
        const seedsNeeded = Math.max(0, 50 - real.length);
        const seeds = SEED_USERS_DAILY.slice(0, seedsNeeded).map(s => ({ ...s, isSeed: true }));
        const combined = [
          ...real.map(r => ({ name: r.player_name, title: r.job_title, location: r.location, score: r.score, game_mode: r.game_mode, isSeed: false, isMe: r.user_id === currentUser?.id })),
          ...seeds,
        ].sort((a, b) => b.score - a.score).slice(0, 50);
        setLeaderboard(combined);
      } catch { setLeaderboard(SEED_USERS_DAILY.map(s => ({ ...s, isSeed: true }))); }
      setLoading(false);
    };
    load();
  }, []);

  const totalPlayers = weeklyGames + Math.min(SEED_USERS_DAILY.length, Math.max(0, 50 - weeklyGames));
  const myRank = leaderboard.findIndex(e => e.isMe) + 1;
  const medals = ["🥇", "🥈", "🥉"];

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 200, background: "rgba(15,23,42,0.5)", backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20, fontFamily: "'Inter', sans-serif" }} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={{ background: "#ffffff", borderRadius: 16, width: "100%", maxWidth: 500, maxHeight: "85vh", display: "flex", flexDirection: "column", border: "1px solid #e2e8f0", boxShadow: "0 20px 60px rgba(15,23,42,0.15)", overflow: "hidden" }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid #e2e8f0", display: "flex", alignItems: "center", justifyContent: "space-between", flexShrink: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ fontSize: 16 }}>🏆</span>
            <div>
              <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>Weekly Leaderboard</div>
              <div style={{ fontSize: 11, color: "#94a3b8" }}>Resets {getNextSundayReset()}</div>
            </div>
          </div>
          <button onClick={onClose} style={{ background: "none", border: "none", color: "#94a3b8", fontSize: 20, cursor: "pointer", lineHeight: 1, padding: "2px 6px" }}>×</button>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", borderBottom: "1px solid #e2e8f0", flexShrink: 0 }}>
          {[{ label: "TOP SCORE", val: leaderboard[0]?.score || "—", color: leaderboard[0]?.score ? scoreColor(leaderboard[0].score).text : "#16a34a" }, { label: "PLAYERS", val: `${totalPlayers}+`, color: "#1d4ed8" }, { label: "YOUR RANK", val: myRank > 0 ? `#${myRank}` : isPro ? "Play!" : "—", color: "#16a34a" }].map((s, i) => (
            <div key={i} style={{ padding: "12px 8px", textAlign: "center", borderRight: i < 2 ? "1px solid #e2e8f0" : "none" }}>
              <div style={{ fontSize: 20, fontWeight: 800, color: s.color, marginBottom: 2 }}>{s.val}</div>
              <div style={{ fontSize: 9, color: "#94a3b8", fontWeight: 600, letterSpacing: "0.08em" }}>{s.label}</div>
            </div>
          ))}
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: "12px 16px" }}>
          {loading ? (
            <div style={{ textAlign: "center", padding: "32px 0", color: "#94a3b8", fontSize: 13 }}>Loading...</div>
          ) : leaderboard.map((entry, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 12px", borderRadius: 8, background: entry.isMe ? "#eff6ff" : "#ffffff", border: `1px solid ${entry.isMe ? "#bfdbfe" : "#f1f5f9"}`, marginBottom: 4, opacity: entry.isSeed ? 0.7 : 1 }}>
              <div style={{ width: 20, textAlign: "center", fontSize: i < 3 ? 14 : 10, fontWeight: 700, color: "#94a3b8", flexShrink: 0 }}>{i < 3 ? medals[i] : `#${i + 1}`}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: entry.isMe ? "#1d4ed8" : "#0f172a", display: "flex", alignItems: "center", gap: 5 }}>
                  {entry.name}
                  {entry.isMe && <span style={{ fontSize: 8, background: "#eff6ff", color: "#1d4ed8", border: "1px solid #bfdbfe", borderRadius: 3, padding: "1px 4px", fontWeight: 700 }}>YOU</span>}
                </div>
                <div style={{ fontSize: 10, color: "#94a3b8", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{entry.title} · {entry.location}</div>
              </div>
              <div style={{ fontSize: 16, fontWeight: 800, color: scoreColor(entry.score).text, flexShrink: 0 }}>{entry.score}</div>
            </div>
          ))}
        </div>
        <div style={{ padding: "14px 16px", borderTop: "1px solid #e2e8f0", flexShrink: 0 }}>
          {isPro ? (
            <button onClick={() => { onClose(); onPlay(); }} style={{ width: "100%", padding: "12px", borderRadius: 10, border: "none", background: "#0f172a", color: "#fff", fontSize: 13, fontWeight: 700, cursor: "pointer" }}>
              ⚔️ Play Close or Lose — Claim Your Spot
            </button>
          ) : (
            <div style={{ textAlign: "center" }}>
              <div style={{ fontSize: 12, color: "#64748b", marginBottom: 10 }}>Want to compete? Close or Lose is a <strong style={{ color: "#0f172a" }}>Pro</strong> feature.</div>
              <button onClick={onClose} style={{ width: "100%", padding: "12px", borderRadius: 10, border: "none", background: "#0f172a", color: "#fff", fontSize: 13, fontWeight: 700, cursor: "pointer" }}>
                ⚡ Upgrade to Pro — $29/mo
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Components ────────────────────────────────────────────────────────────────

function TypingDots() {
  return (
    <div style={{ display: "flex", gap: 5, padding: "4px 0", alignItems: "center" }}>
      {[0,1,2].map(i => (
        <div key={i} style={{
          width: 6, height: 6, borderRadius: "50%", background: "#4b5563",
          animation: "bounceDot 1.2s infinite", animationDelay: `${i * 0.18}s`,
        }} />
      ))}
    </div>
  );
}

function renderMarkdown(text) {
  if (!text) return null;
  const lines = text.split("\n");
  const elements = [];
  let key = 0;
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    if (/^---+$/.test(line.trim())) {
      elements.push(<hr key={key++} style={{ border: "none", borderTop: "1px solid #e2e8f0", margin: "10px 0" }} />);
      continue;
    }
    if (/^#{1,3}\s/.test(line)) {
      const lvl = line.match(/^(#+)/)[1].length;
      const txt = line.replace(/^#+\s+/, "");
      const sz = lvl === 1 ? 15 : lvl === 2 ? 14 : 13;
      elements.push(<div key={key++} style={{ fontWeight: 700, fontSize: sz, marginTop: 10, marginBottom: 4, color: "#0f172a" }}>{renderInline(txt)}</div>);
      continue;
    }
    if (/^[-*]\s/.test(line)) {
      elements.push(<div key={key++} style={{ display: "flex", gap: 6, marginBottom: 2 }}><span style={{ color: "#94a3b8", flexShrink: 0 }}>•</span><span>{renderInline(line.replace(/^[-*]\s/, ""))}</span></div>);
      continue;
    }
    if (/^\d+\.\s/.test(line)) {
      const num = line.match(/^(\d+)\./)[1];
      elements.push(<div key={key++} style={{ display: "flex", gap: 6, marginBottom: 2 }}><span style={{ color: "#94a3b8", flexShrink: 0, minWidth: 16 }}>{num}.</span><span>{renderInline(line.replace(/^\d+\.\s/, ""))}</span></div>);
      continue;
    }
    if (line.trim() === "") {
      elements.push(<div key={key++} style={{ height: 6 }} />);
      continue;
    }
    elements.push(<div key={key++} style={{ marginBottom: 2 }}>{renderInline(line)}</div>);
  }
  return elements;
}

function renderInline(text) {
  const parts = [];
  const regex = /(\*\*\*(.+?)\*\*\*|\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`)/g;
  let last = 0, match, key = 0;
  while ((match = regex.exec(text)) !== null) {
    if (match.index > last) parts.push(<span key={key++}>{text.slice(last, match.index)}</span>);
    if (match[2]) parts.push(<strong key={key++} style={{ fontStyle: "italic" }}>{match[2]}</strong>);
    else if (match[3]) parts.push(<strong key={key++}>{match[3]}</strong>);
    else if (match[4]) parts.push(<em key={key++}>{match[4]}</em>);
    else if (match[5]) parts.push(<code key={key++} style={{ background: "#f1f5f9", borderRadius: 3, padding: "1px 5px", fontSize: 12, fontFamily: "monospace" }}>{match[5]}</code>);
    last = match.index + match[0].length;
  }
  if (last < text.length) parts.push(<span key={key++}>{text.slice(last)}</span>);
  return parts.length ? parts : text;
}

function Message({ msg }) {
  const isUser = msg.role === "user";
  return (
    <div style={{
      display: "flex", justifyContent: isUser ? "flex-end" : "flex-start",
      marginBottom: 16, animation: "msgIn 0.22s ease forwards",
      gap: 10, alignItems: "flex-start",
    }}>
      {!isUser && (
        <div style={{
          width: 44, height: 30, borderRadius: 6, flexShrink: 0,
          background: "#f9fafb", border: "1.5px solid #d1d5db",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 10, fontFamily: "'Inter', sans-serif",
          color: "#4b5563", fontWeight: 700, marginTop: 2,
        }}>Coach</div>
      )}
      <div style={{
        maxWidth: "82%", padding: "11px 16px",
        borderRadius: isUser ? "12px 12px 3px 12px" : "3px 12px 12px 12px",
        background: isUser ? "#1e293b" : "#ffffff",
        border: isUser ? "none" : "1px solid #e2e8f0",
        color: isUser ? "#ffffff" : "#1e293b",
        fontSize: 13.5, lineHeight: 1.75,
        boxShadow: isUser ? "0 2px 12px rgba(30,41,59,0.18)" : "0 1px 4px rgba(0,0,0,0.06)",
        wordBreak: "break-word",
        fontFamily: "'Inter', sans-serif",
      }}>
        {isUser ? msg.content : renderMarkdown(msg.content)}
      </div>
      {isUser && (
        <div style={{
          width: 30, height: 30, borderRadius: 6, flexShrink: 0,
          background: "#f8fafc", border: "1.5px solid #e2e8f0",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 11, fontFamily: "'Inter', sans-serif",
          color: "#64748b", fontWeight: 700, marginTop: 2,
        }}>YOU</div>
      )}
    </div>
  );
}

// ─── Prompt Input Modal ───────────────────────────────────────────────────────
// Shown when a quick-action button has a placeholder prompt that needs user input
function PromptInputModal({ config, onSubmit, onClose, prefilled }) {
  const [value, setValue] = React.useState(prefilled || "");
  const textareaRef = React.useRef(null);
  React.useEffect(() => { setTimeout(() => textareaRef.current?.focus(), 80); }, []);
  const handleSubmit = () => {
    if (!value.trim()) return;
    onSubmit(config.prefix + value.trim());
    onClose();
  };
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 300, background: "rgba(15,23,42,0.5)", backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20, fontFamily: "'Inter', sans-serif" }}>
      <div style={{ background: "#fff", borderRadius: 16, padding: "28px 24px", maxWidth: 480, width: "100%", border: "1px solid #e2e8f0", boxShadow: "0 20px 60px rgba(15,23,42,0.15)" }}>
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 16 }}>
          <div>
            <div style={{ fontSize: 16, fontWeight: 700, color: "#0f172a", marginBottom: 4 }}>{config.title}</div>
            <div style={{ fontSize: 13, color: "#64748b", lineHeight: 1.5 }}>{config.subtitle}</div>
          </div>
          <button onClick={onClose} style={{ background: "none", border: "none", color: "#94a3b8", fontSize: 20, cursor: "pointer", padding: "0 4px", lineHeight: 1, flexShrink: 0 }}>×</button>
        </div>
        <textarea
          ref={textareaRef}
          value={value}
          onChange={e => setValue(e.target.value)}
          onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSubmit(); } }}
          placeholder={config.placeholder}
          rows={config.rows || 4}
          style={{ width: "100%", padding: "12px 14px", borderRadius: 10, border: "1px solid #e2e8f0", background: "#f8fafc", fontSize: 13, color: "#0f172a", fontFamily: "'Inter', sans-serif", outline: "none", resize: "vertical", lineHeight: 1.65, boxSizing: "border-box", marginBottom: 14 }}
        />
        <div style={{ display: "flex", gap: 8 }}>
          <button onClick={handleSubmit} disabled={!value.trim()} style={{ flex: 1, padding: "12px", borderRadius: 9, border: "none", background: value.trim() ? "#0f172a" : "#f1f5f9", color: value.trim() ? "#fff" : "#94a3b8", fontSize: 14, fontWeight: 700, cursor: value.trim() ? "pointer" : "not-allowed", fontFamily: "'Inter', sans-serif" }}>
            {config.cta || "Send to Coach →"}
          </button>
          <button onClick={onClose} style={{ padding: "12px 16px", borderRadius: 9, border: "1px solid #e2e8f0", background: "transparent", color: "#64748b", fontSize: 13, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Cancel</button>
        </div>
        <div style={{ textAlign: "center", marginTop: 10, fontSize: 11, color: "#94a3b8" }}>Enter to send · Shift+Enter for new line</div>
      </div>
    </div>
  );
}

// Prompt configs for each command that needs user input
const PROMPT_INPUT_CONFIGS = {
  "OUTREACH:": {
    title: "Cold Outreach Coach",
    subtitle: "Paste your cold email or LinkedIn message. Coach will score it, tear it apart, and rewrite it.",
    placeholder: "Paste your cold email or LinkedIn message here...",
    prefix: "OUTREACH: ",
    rows: 6,
    cta: "Analyze my outreach →",
  },
  "TONE:": {
    title: "Tone & Pacing Coach",
    subtitle: "Paste any script or pitch. Coach will analyze the tonality word-by-word.",
    placeholder: "Paste your script or pitch here...",
    prefix: "TONE: ",
    rows: 6,
    cta: "Analyze my tone →",
  },
  "FOLLOWUP:": {
    title: "Follow-Up Generator",
    subtitle: "Describe your last call and where the deal stands. Coach will write email, text, and voicemail follow-ups.",
    placeholder: "e.g. Had a solid discovery call with a homeowner interested in flooring. They said they liked it but needed to talk to their spouse. It's been 4 days.",
    prefix: "FOLLOWUP: ",
    rows: 4,
    cta: "Generate follow-ups →",
  },
  "SCRIPT:": {
    title: "Script Rewriter",
    subtitle: "Paste your script, pitch, or message. Coach will rewrite it with a Best Version and an Alternate.",
    placeholder: "Paste your script or message here...",
    prefix: "SCRIPT: ",
    rows: 5,
    cta: "Rewrite my script →",
  },
  "DISCOVERY:": {
    title: "Discovery Questions",
    subtitle: "Describe your product and situation. Coach will generate 6-10 targeted discovery questions.",
    placeholder: "e.g. in-home kitchen remodeling consultation with a homeowner who just moved in",
    prefix: "DISCOVERY: ",
    rows: 3,
    cta: "Generate questions →",
  },
};

function ProPaywall({ onClose, userId }) {
  const proFeatures = [
    "🎭 Realistic buyer roleplay simulations",
    "⚡ Objection drill mode with live critique",
    "📨 Cold Outreach Coach — score & rewrite",
    "📞 Follow-Up Generator (email, text, voicemail)",
    "🎙️ Tonality & Pacing Coach",
    "🏢 Full deal cycle simulations",
    "📋 Call transcript analysis",
    "📊 Deal coaching & risk analysis",
    "🧑‍💼 Rep Onboarding Mode (5-session program)",
    "🎯 Custom Persona Builder",
    "🏆 Close Intelligence Score (0–100)",
    "📈 Weekly performance summaries",
  ];

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 100,
      background: "rgba(15,23,42,0.6)", backdropFilter: "blur(4px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
      overflowY: "auto",
    }}>
      <div style={{
        background: "#ffffff", borderRadius: 16, padding: "32px 28px",
        maxWidth: 560, width: "100%",
        boxShadow: "0 24px 64px rgba(0,0,0,0.15)", border: "1px solid #e2e8f0",
        maxHeight: "95vh", overflowY: "auto",
      }}>
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 6 }}>
          <div>
            <div style={{ fontSize: 20, fontWeight: 700, color: "#0f172a", marginBottom: 6, fontFamily: "'Inter', sans-serif" }}>
              Upgrade {BRAND_CONFIG.appName}
            </div>
            <div style={{ fontSize: 13, color: "#64748b", fontFamily: "'Inter', sans-serif", lineHeight: 1.5 }}>
              Choose the plan that fits your team. Cancel anytime.
            </div>
          </div>
          <button onClick={onClose} style={{
            background: "none", border: "none", cursor: "pointer",
            color: "#94a3b8", fontSize: 22, lineHeight: 1, padding: "2px 4px", flexShrink: 0,
          }}>×</button>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, margin: "24px 0" }}>
          <div style={{
            padding: "20px 18px", borderRadius: 12,
            border: "2px solid #1e293b", background: "#ffffff",
            position: "relative",
          }}>
            <div style={{
              position: "absolute", top: -11, left: 16,
              background: "#1e293b", color: "#fff",
              fontSize: 10, fontWeight: 700, padding: "3px 10px",
              borderRadius: 20, letterSpacing: "0.08em", fontFamily: "'Inter', sans-serif",
            }}>MOST POPULAR</div>
            <div style={{ fontSize: 13, fontWeight: 700, color: "#1e293b", marginBottom: 4, fontFamily: "'Inter', sans-serif" }}>
              (Pro)
            </div>
            <div style={{ marginBottom: 12 }}>
              <span style={{ fontSize: 26, fontWeight: 700, color: "#0f172a", fontFamily: "'Inter', sans-serif" }}>$29</span>
              <span style={{ fontSize: 12, color: "#94a3b8", fontFamily: "'Inter', sans-serif" }}>/mo</span>
            </div>
            <div style={{ fontSize: 11.5, color: "#64748b", marginBottom: 14, fontFamily: "'Inter', sans-serif", lineHeight: 1.5 }}>
              For individual sales reps — in-home or SaaS/AE.
            </div>
            {proFeatures.slice(0, 6).map((f, i) => (
              <div key={i} style={{ display: "flex", gap: 7, alignItems: "flex-start", marginBottom: 6 }}>
                <span style={{ color: "#1e293b", fontSize: 11, marginTop: 1 }}>✓</span>
                <span style={{ fontSize: 11.5, color: "#374151", fontFamily: "'Inter', sans-serif" }}>{f.replace(/^.{2}/, "").trim()}</span>
              </div>
            ))}
            <a href={stripeLink(STRIPE_PRO_LINK, userId)} target="_blank" rel="noreferrer" style={{ textDecoration: "none" }}>
              <button style={{
                width: "100%", padding: "11px", borderRadius: 9, marginTop: 14,
                background: "#1e293b", border: "none",
                color: "#fff", fontSize: 13, fontWeight: 600,
                cursor: "pointer", fontFamily: "'Inter', sans-serif",
              }}>Get (Pro) →</button>
            </a>
          </div>

          <div style={{
            padding: "20px 18px", borderRadius: 12,
            border: "2px solid #1e293b", background: "#0f172a",
            position: "relative",
          }}>
            <div style={{
              position: "absolute", top: -11, right: 16,
              background: "#3b82f6", color: "#fff",
              fontSize: 10, fontWeight: 700, padding: "3px 10px",
              borderRadius: 20, letterSpacing: "0.08em", fontFamily: "'Inter', sans-serif",
            }}>👥 FOR TEAMS</div>
            <div style={{ fontSize: 13, fontWeight: 700, color: "#e2e8f0", marginBottom: 4, fontFamily: "'Inter', sans-serif" }}>
              Team
            </div>
            <div style={{ marginBottom: 2 }}>
              <span style={{ fontSize: 32, fontWeight: 800, color: "#ffffff", fontFamily: "'Inter', sans-serif" }}>$199</span>
              <span style={{ fontSize: 12, color: "#64748b", fontFamily: "'Inter', sans-serif" }}>/mo</span>
            </div>
            <div style={{ fontSize: 11, color: "#3b82f6", fontWeight: 600, marginBottom: 4, fontFamily: "'Inter', sans-serif" }}>Up to 10 users</div>
            <div style={{ fontSize: 11, color: "#475569", marginBottom: 6, fontFamily: "'Inter', sans-serif" }}>Flat rate — no per-seat fees</div>
            <div style={{ padding: "7px 10px", borderRadius: 7, background: "rgba(59,130,246,0.12)", border: "1px solid rgba(59,130,246,0.2)", marginBottom: 14 }}>
              <span style={{ fontSize: 11, color: "#93c5fd", fontFamily: "'Inter', sans-serif" }}>
                💡 That's <strong style={{ color: "#ffffff" }}>$19.90/user</strong> — vs $29 on Pro. Every user gets full Pro access.
              </span>
            </div>
            {[
              "Everything in (Pro) for all seats",
              "Up to 10 users included",
              "Manager performance dashboard",
              "Team Close Intelligence leaderboard",
              "Shared objection library",
              "Priority support",
            ].map((f, i) => (
              <div key={i} style={{ display: "flex", gap: 7, alignItems: "flex-start", marginBottom: 6 }}>
                <span style={{ color: "#3b82f6", fontSize: 11, marginTop: 1 }}>✓</span>
                <span style={{ fontSize: 11.5, color: "#94a3b8", fontFamily: "'Inter', sans-serif" }}>{f}</span>
              </div>
            ))}
            <a href={stripeLink(STRIPE_TEAM_LINK, userId)} target="_blank" rel="noreferrer" style={{ textDecoration: "none" }}>
              <button style={{
                width: "100%", padding: "11px", borderRadius: 9, marginTop: 14,
                background: "#3b82f6", border: "none",
                color: "#fff", fontSize: 13, fontWeight: 600,
                cursor: "pointer", fontFamily: "'Inter', sans-serif",
              }}>Get Team →</button>
            </a>
          </div>
        </div>

        {/* Enterprise tier */}
        <div style={{
          padding: "20px 22px", borderRadius: 12, marginBottom: 16,
          border: "1.5px solid #bfdbfe", background: "#f8fafc",
          position: "relative",
        }}>
          <div style={{
            position: "absolute", top: -11, left: 16,
            background: "#3b82f6", color: "#fff",
            fontSize: 10, fontWeight: 700, padding: "3px 12px",
            borderRadius: 20, letterSpacing: "0.08em", fontFamily: "'Inter', sans-serif",
          }}>🏢 ENTERPRISE</div>
          <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
            <div style={{ flex: 1, minWidth: 200 }}>
              <div style={{ fontSize: 15, fontWeight: 700, color: "#0f172a", marginBottom: 4, fontFamily: "'Inter', sans-serif" }}>Enterprise Edition</div>
              <div style={{ fontSize: 12, color: "#64748b", marginBottom: 14, fontFamily: "'Inter', sans-serif", lineHeight: 1.5 }}>
                For sales teams, SaaS companies, startups, and enterprise organizations looking to improve sales performance at scale.
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
                {[
                  "Optional white label platform",
                  "Team Performance Command Center",
                  "2× token usage vs Pro & Team",
                  "Private Sales Arena",
                  "AI Coaching Insights",
                  "Enterprise onboarding",
                ].map((f, i) => (
                  <div key={i} style={{ display: "flex", gap: 6, alignItems: "flex-start" }}>
                    <span style={{ color: "#3b82f6", fontSize: 11, marginTop: 1, flexShrink: 0 }}>✓</span>
                    <span style={{ fontSize: 11.5, color: "#475569", fontFamily: "'Inter', sans-serif", lineHeight: 1.4 }}>{f}</span>
                  </div>
                ))}
              </div>
            </div>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <div style={{ fontSize: 13, color: "#64748b", marginBottom: 8, fontFamily: "'Inter', sans-serif", textAlign: "center" }}>Custom pricing — let's talk.</div>
              <a href="https://docs.google.com/forms/d/e/1FAIpQLSeOLOobsAywU9nZ3j-s1BC8DdEROWTwzNgBAfkRP5OugFVSVw/viewform?usp=header" target="_blank" rel="noreferrer" style={{ textDecoration: "none" }}>
                <button style={{
                  padding: "11px 24px", borderRadius: 9, border: "none",
                  background: "#3b82f6", color: "#fff", fontSize: 13, fontWeight: 700,
                  cursor: "pointer", fontFamily: "'Inter', sans-serif", whiteSpace: "nowrap",
                }}>Request Enterprise Access →</button>
              </a>
            </div>
          </div>
        </div>

        <div style={{
          padding: "12px 16px", borderRadius: 10,
          background: "#eff6ff", border: "1px solid #bfdbfe",
          fontSize: 12, color: "#1d4ed8", fontFamily: "'Inter', sans-serif",
          marginBottom: 16, lineHeight: 1.5,
        }}>
          💡 <strong>Team = $199/mo for up to 10 users</strong> — that's $91 cheaper than 10 individual Pro plans, plus the full manager dashboard.
        </div>

        <button onClick={onClose} style={{
          width: "100%", padding: "10px", borderRadius: 10,
          background: "transparent", border: "1px solid #e2e8f0",
          color: "#64748b", fontSize: 13, cursor: "pointer", fontFamily: "'Inter', sans-serif",
        }}>Maybe later</button>
        <div style={{ textAlign: "center", marginTop: 12, display: "flex", justifyContent: "center", gap: 16, flexWrap: "wrap" }}>
          {[["Privacy Policy", "/privacy-policy.html"], ["Terms", "/terms-of-service.html"], ["Refund Policy", "/refund-policy.html"]].map(([label, href]) => (
            <a key={label} href={href} target="_blank" rel="noreferrer" style={{ fontSize: 10, color: "#cbd5e1", textDecoration: "none", fontFamily: "'Inter', sans-serif" }}>{label}</a>
          ))}
        </div>
      </div>
    </div>
  );
}

function AffiliateDashboard({ isPro, onClose, userId }) {
  const [activeTab, setActiveTab] = useState("overview");

  const shareMessages = [
    { platform: "LinkedIn", icon: "💼", msg: "I've been using SalesLab AI to sharpen my objection handling and close more deals. It's like having a personal sales coach available 24/7. Get started free: https://thesaleslabai.com" },
    { platform: "Text/SMS", icon: "💬", msg: "Hey! Found this AI sales coach that's been helping me close more deals. Free to start: https://thesaleslabai.com" },
    { platform: "Email", icon: "📧", msg: "Subject: Tool that's been helping me close more\n\nHey,\n\nWanted to share a tool I've been using called SalesLab AI. It helps with objection handling, script rewrites, and deal coaching. Free to try:\nhttps://thesaleslabai.com" },
    { platform: "Facebook/Instagram", icon: "📱", msg: "Just found the best sales training tool — SalesLab AI. Practice objections, rewrite your scripts, get deal coaching with AI. Free to start 👇\nhttps://thesaleslabai.com" },
  ];

  const assets = [
    { name: "Square Post (1080×1080)", file: "/social-square.png", icon: "🖼️", desc: "Instagram, Facebook" },
    { name: "Story (1080×1920)", file: "/social-story.png", icon: "📱", desc: "IG Story, TikTok" },
    { name: "Banner (1500×500)", file: "/social-banner.png", icon: "🎯", desc: "Twitter/X header" },
    { name: "Landscape (1200×628)", file: "/social-landscape.png", icon: "💻", desc: "LinkedIn, Facebook" },
    { name: "Affiliate Toolkit + Landing Page Generator", file: "/saleslab-affiliate-toolkit.html", icon: "🧰", desc: "Custom landing pages by industry, scripts & more" },
    { name: "Ad Creatives (4 sizes)", file: "/saleslab-affiliate-ads.html", icon: "📣", desc: "Banner ads" },
  ];

  const tabs = ["overview", "assets", "share"];

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 100,
      background: "#f8fafc", display: "flex", flexDirection: "column",
      fontFamily: "'Inter', sans-serif",
    }}>
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "0 24px", height: 56, background: "#ffffff",
        borderBottom: "1px solid #e2e8f0", flexShrink: 0,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ fontSize: 18 }}>🤝</span>
          <span style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>Affiliate Program</span>
          <span style={{ fontSize: 10, background: "#f0fdf4", color: "#16a34a", border: "1px solid #86efac", borderRadius: 4, padding: "2px 8px", fontWeight: 600 }}>30% Recurring</span>
        </div>
        <button onClick={onClose} style={{
          background: "transparent", border: "1px solid #e2e8f0",
          color: "#64748b", borderRadius: 6, padding: "5px 14px",
          fontSize: 11, cursor: "pointer",
        }}>← Back to Chat</button>
      </div>

      <div style={{ display: "flex", background: "#ffffff", borderBottom: "1px solid #e2e8f0", padding: "0 24px", flexShrink: 0 }}>
        {tabs.map(tab => (
          <button key={tab} onClick={() => setActiveTab(tab)} style={{
            padding: "12px 20px", background: "none", border: "none",
            borderBottom: activeTab === tab ? "2px solid #3b82f6" : "2px solid transparent",
            color: activeTab === tab ? "#3b82f6" : "#64748b",
            fontSize: 12, fontWeight: 600, cursor: "pointer",
            textTransform: "capitalize", letterSpacing: "0.04em",
          }}>{tab === "overview" ? "Overview" : tab === "assets" ? "Digital Assets" : "Share Messages"}</button>
        ))}
      </div>

      <div style={{ flex: 1, overflowY: "auto", padding: 24 }}>
        {activeTab === "overview" && (
          <div style={{ maxWidth: 640, margin: "0 auto" }}>
            <div style={{ background: "#ffffff", borderRadius: 12, padding: 24, border: "1px solid #e2e8f0", marginBottom: 16 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
                <div style={{ width: 28, height: 28, borderRadius: 7, background: "#3b82f6", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, color: "#fff", flexShrink: 0 }}>1</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>Apply to the affiliate program</div>
              </div>
              <div style={{ fontSize: 13, color: "#64748b", marginBottom: 16, lineHeight: 1.6 }}>
                The affiliate program is coming soon. Get on the early access list now and be first to know when it launches, with the best commission tier locked in from day one.
              </div>
              <a href="https://docs.google.com/forms/d/e/1FAIpQLSeOLOobsAywU9nZ3j-s1BC8DdEROWTwzNgBAfkRP5OugFVSVw/viewform?usp=header" target="_blank" rel="noreferrer" style={{ textDecoration: "none" }}>
                <button style={{
                  width: "100%", padding: "12px", borderRadius: 9,
                  background: "#1e293b", border: "none", color: "#ffffff",
                  fontSize: 13, fontWeight: 700, cursor: "pointer",
                }}>Apply Now on Lemon Squeezy →</button>
              </a>
            </div>

            <div style={{ background: "#ffffff", borderRadius: 12, padding: 24, border: "1px solid #e2e8f0", marginBottom: 16 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
                <div style={{ width: 28, height: 28, borderRadius: 7, background: "#3b82f6", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, color: "#fff", flexShrink: 0 }}>2</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>Earn 30% recurring — every month</div>
              </div>
              <div style={{ fontSize: 13, color: "#64748b", lineHeight: 1.6, marginBottom: 14 }}>
                No caps. No expiry. A subscriber you referred in January is still paying you commission in December.
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
                {[{ refs: "5 Pro users", earn: "$43.50/mo" }, { refs: "1 Team account", earn: "$59.70/mo" }, { refs: "10 Teams", earn: "$597/mo" }].map((e, i) => (
                  <div key={i} style={{ textAlign: "center", padding: "12px", background: "#f8fafc", border: "1px solid #e2e8f0", borderRadius: 9 }}>
                    <div style={{ fontSize: 18, fontWeight: 700, color: "#1e293b" }}>{e.earn}</div>
                    <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 3 }}>{e.refs}</div>
                  </div>
                ))}
              </div>
            </div>

            <a href="https://docs.google.com/forms/d/e/1FAIpQLSeOLOobsAywU9nZ3j-s1BC8DdEROWTwzNgBAfkRP5OugFVSVw/viewform?usp=header" target="_blank" rel="noreferrer" style={{ textDecoration: "none", display: "block" }}>
              <div style={{
                background: "linear-gradient(135deg, #3b82f6, #2563eb)",
                borderRadius: 12, padding: 20, display: "flex", alignItems: "center", justifyContent: "space-between",
              }}>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 700, color: "#ffffff", marginBottom: 3 }}>Already an affiliate?</div>
                  <div style={{ fontSize: 12, color: "rgba(255,255,255,0.75)" }}>View your link, clicks, commissions & payouts on Lemon Squeezy</div>
                </div>
                <span style={{ fontSize: 26 }}>💰</span>
              </div>
            </a>
          </div>
        )}

        {activeTab === "assets" && (
          <div style={{ maxWidth: 720, margin: "0 auto" }}>
            <div style={{ fontSize: 13, color: "#64748b", marginBottom: 12 }}>Download these assets to promote {BRAND_CONFIG.appName} on social media and your website.</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              {assets.map((asset, i) => (
                <a key={i} href={asset.file} target="_blank" rel="noreferrer" download style={{ textDecoration: "none" }}>
                  <div style={{ background: "#ffffff", borderRadius: 12, padding: 20, border: "1px solid #e2e8f0", cursor: "pointer", display: "flex", gap: 14, alignItems: "center" }}>
                    <span style={{ fontSize: 28 }}>{asset.icon}</span>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 600, color: "#0f172a", marginBottom: 3 }}>{asset.name}</div>
                      <div style={{ fontSize: 11, color: "#94a3b8" }}>{asset.desc}</div>
                    </div>
                    <div style={{ marginLeft: "auto", fontSize: 16, color: "#cbd5e1" }}>↓</div>
                  </div>
                </a>
              ))}
            </div>
          </div>
        )}

        {activeTab === "share" && (
          <div style={{ maxWidth: 640, margin: "0 auto" }}>
            <div style={{ fontSize: 13, color: "#64748b", marginBottom: 8 }}>Copy these messages to share {BRAND_CONFIG.appName}. Your personal affiliate link will be sent when the program launches.</div>
            <a href="https://docs.google.com/forms/d/e/1FAIpQLSeOLOobsAywU9nZ3j-s1BC8DdEROWTwzNgBAfkRP5OugFVSVw/viewform?usp=header" target="_blank" rel="noreferrer" style={{ textDecoration: "none", display: "block", marginBottom: 20 }}>
              <div style={{ background: "#eff6ff", border: "1px solid #bfdbfe", borderRadius: 9, padding: "10px 14px", fontSize: 12, color: "#2563eb", fontWeight: 600 }}>
                📎 Join the waitlist to get early access
              </div>
            </a>
            {shareMessages.map((m, i) => (
              <div key={i} style={{ background: "#ffffff", borderRadius: 12, padding: 20, border: "1px solid #e2e8f0", marginBottom: 16 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ fontSize: 16 }}>{m.icon}</span>
                    <span style={{ fontSize: 12, fontWeight: 700, color: "#0f172a" }}>{m.platform}</span>
                  </div>
                  <button onClick={() => navigator.clipboard.writeText(m.msg)} style={{
                    padding: "5px 12px", borderRadius: 6, background: "#f8fafc",
                    border: "1px solid #e2e8f0", color: "#475569", fontSize: 11, fontWeight: 600, cursor: "pointer",
                  }}>Copy</button>
                </div>
                <div style={{ fontSize: 12, color: "#374151", lineHeight: 1.7, background: "#f8fafc", padding: "12px 14px", borderRadius: 8, whiteSpace: "pre-wrap" }}>{m.msg}</div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function SupportPage({ onClose, userEmail }) {
  const [form, setForm] = useState({ name: "", email: userEmail || "", subject: "", message: "" });
  const [submitted, setSubmitted] = useState(false);
  const [sending, setSending] = useState(false);

  const subjects = [
    "I can't log in",
    "Billing or subscription issue",
    "Feature not working",
    "Question about my plan",
    "Affiliate program question",
    "Other",
  ];

  const handleSubmit = () => {
    if (!form.name || !form.email || !form.subject || !form.message) return;
    setSending(true);
    const body = encodeURIComponent(`Name: ${form.name}\nEmail: ${form.email}\n\n${form.message}`);
    const subject = encodeURIComponent(`[${BRAND_CONFIG.appName} Support] ${form.subject}`);
    window.open(`mailto:{BRAND_CONFIG.supportEmail}?subject=${subject}&body=${body}`, "_blank");
    setTimeout(() => { setSending(false); setSubmitted(true); }, 600);
  };

  const inputStyle = {
    width: "100%", padding: "10px 12px", borderRadius: 8,
    border: "1px solid #e2e8f0", fontSize: 13, color: "#374151",
    fontFamily: "'Inter', sans-serif", background: "#ffffff",
    boxSizing: "border-box", outline: "none",
  };

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 100,
      background: "#f8fafc", display: "flex", flexDirection: "column",
      fontFamily: "'Inter', sans-serif",
    }}>
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "0 24px", height: 56, background: "#ffffff",
        borderBottom: "1px solid #e2e8f0", flexShrink: 0,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ fontSize: 18 }}>🎧</span>
          <span style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>Help & Support</span>
        </div>
        <button onClick={onClose} style={{
          background: "transparent", border: "1px solid #e2e8f0",
          color: "#64748b", borderRadius: 6, padding: "5px 14px",
          fontSize: 11, cursor: "pointer",
        }}>← Back to Chat</button>
      </div>

      <div style={{ flex: 1, overflowY: "auto", padding: 24 }}>
        <div style={{ maxWidth: 560, margin: "0 auto" }}>
          {!submitted ? (
            <>
              <div style={{ fontSize: 13, color: "#64748b", marginBottom: 24, lineHeight: 1.6 }}>
                We typically respond within 24 hours. Fill out the form below or email us directly at{" "}
                <a href="mailto:{BRAND_CONFIG.supportEmail}" style={{ color: "#3b82f6", textDecoration: "none", fontWeight: 600 }}>
                  {BRAND_CONFIG.supportEmail}
                </a>
              </div>

              <div style={{ background: "#ffffff", borderRadius: 12, padding: 24, border: "1px solid #e2e8f0", marginBottom: 20 }}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 600, color: "#374151", marginBottom: 6 }}>Your Name</div>
                    <input style={inputStyle} placeholder="First Last" value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} />
                  </div>
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 600, color: "#374151", marginBottom: 6 }}>Your Email</div>
                    <input style={inputStyle} placeholder="you@email.com" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} />
                  </div>
                </div>

                <div style={{ marginBottom: 14 }}>
                  <div style={{ fontSize: 11, fontWeight: 600, color: "#374151", marginBottom: 6 }}>Subject</div>
                  <select style={{ ...inputStyle, appearance: "none", cursor: "pointer" }} value={form.subject} onChange={e => setForm(f => ({ ...f, subject: e.target.value }))}>
                    <option value="">Select a topic...</option>
                    {subjects.map(s => <option key={s} value={s}>{s}</option>)}
                  </select>
                </div>

                <div style={{ marginBottom: 20 }}>
                  <div style={{ fontSize: 11, fontWeight: 600, color: "#374151", marginBottom: 6 }}>Message</div>
                  <textarea style={{ ...inputStyle, height: 130, resize: "vertical" }} placeholder="Describe your issue or question..." value={form.message} onChange={e => setForm(f => ({ ...f, message: e.target.value }))} />
                </div>

                <button onClick={handleSubmit} disabled={!form.name || !form.email || !form.subject || !form.message || sending} style={{
                  width: "100%", padding: "12px", borderRadius: 9,
                  background: (!form.name || !form.email || !form.subject || !form.message) ? "#e2e8f0" : "#1e293b",
                  border: "none",
                  color: (!form.name || !form.email || !form.subject || !form.message) ? "#94a3b8" : "#ffffff",
                  fontSize: 13, fontWeight: 700, cursor: (!form.name || !form.email || !form.subject || !form.message) ? "not-allowed" : "pointer",
                  fontFamily: "'Inter', sans-serif",
                }}>{sending ? "Opening email client..." : "Send Message"}</button>
              </div>
            </>
          ) : (
            <div style={{ textAlign: "center", padding: "60px 20px" }}>
              <div style={{ fontSize: 48, marginBottom: 20 }}>✅</div>
              <div style={{ fontSize: 20, fontWeight: 700, color: "#0f172a", marginBottom: 12 }}>Message sent!</div>
              <div style={{ fontSize: 14, color: "#64748b", lineHeight: 1.7, marginBottom: 28 }}>
                We've received your message and will get back to you at <strong>{form.email}</strong> within 24 hours.
              </div>
              <button onClick={onClose} style={{
                padding: "10px 28px", borderRadius: 9, background: "#1e293b",
                border: "none", color: "#ffffff", fontSize: 13, fontWeight: 600, cursor: "pointer",
                fontFamily: "'Inter', sans-serif",
              }}>Back to Chat</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── TeamDashboard ─────────────────────────────────────────────────────────────
// NOTE: All duplicate useState declarations and duplicate function declarations have been removed.

// ─── Team Leaderboard (extracted to avoid Hook-in-IIFE error) ─────────────────
function TeamLeaderboard({ dashMode, mockReps, partialReps, realReps, avgScore }) {
  const [lbTab, setLbTab] = useState("cis");

  const medals = ["🥇", "🥈", "🥉"];
  const mockSiqReps = [
    { name: "Jordan M.", score: 94, role: "Account Executive", best: "Closing",   weak: "Prospecting" },
    { name: "Aisha T.",  score: 82, role: "SDR",               best: "Closing",   weak: "Prospecting" },
    { name: "Priya S.",  score: 76, role: "BDR",               best: "Discovery", weak: "Negotiation" },
    { name: "Carlos R.", score: 63, role: "AE",                best: "Discovery", weak: "Negotiation" },
    { name: "Derek W.",  score: 51, role: "SDR",               best: "Objection", weak: "Closing" },
  ];
  const cisSorted = dashMode === "demo" ? [...mockReps].sort((a, b) => b.score - a.score)
    : dashMode === "partial" ? [...partialReps].sort((a, b) => b.score - a.score)
    : realReps.filter(r => r.cis_score).sort((a, b) => b.cis_score - a.cis_score);

  return (
    <div style={{ maxWidth: 660, fontFamily: "'Inter', sans-serif" }}>
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 20, fontWeight: 700, color: "#0f172a", marginBottom: 4 }}>Team Leaderboard</div>
        <div style={{ fontSize: 13, color: "#64748b" }}>Two views: Close Intelligence Score (all-time) and Sales IQ (today's daily test).</div>
      </div>

      {/* Sub-tab switcher */}
      <div style={{ display: "flex", gap: 0, background: "#F1F5F9", borderRadius: 10, padding: 4, marginBottom: 20, width: "fit-content" }}>
        {[{ id: "cis", label: "📊 CIS Leaderboard" }, { id: "siq", label: "⚡ Sales IQ · Today" }].map(t => (
          <button key={t.id} onClick={() => setLbTab(t.id)} style={{ padding: "8px 18px", borderRadius: 8, border: "none", background: lbTab === t.id ? "#ffffff" : "transparent", color: lbTab === t.id ? "#1D4ED8" : "#64748b", fontSize: 12.5, fontWeight: lbTab === t.id ? 700 : 500, cursor: "pointer", fontFamily: "'Inter', sans-serif", boxShadow: lbTab === t.id ? "0 1px 4px rgba(0,0,0,0.08)" : "none", transition: "all 0.15s" }}>{t.label}</button>
        ))}
      </div>

      {dashMode === "demo" && <div style={{ fontSize: 11, color: "#1D4ED8", background: "#EFF6FF", border: "0.5px solid #BFDBFE", padding: "8px 14px", borderRadius: 8, marginBottom: 16, fontWeight: 600 }}>Sample data — invite your first rep to see real rankings</div>}
      {dashMode === "partial" && <div style={{ fontSize: 11, color: "#1D4ED8", background: "#EFF6FF", border: "0.5px solid #BFDBFE", padding: "8px 14px", borderRadius: 8, marginBottom: 16, fontWeight: 600 }}>Your reps have joined — scores will appear after their first session.</div>}

      {/* ── CIS TAB ── */}
      {lbTab === "cis" && (
        <div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12, marginBottom: 20 }}>
            {[
              { label: "TOP CIS SCORE", val: cisSorted[0] ? (dashMode === "live" ? cisSorted[0].cis_score : cisSorted[0].score) : "—", color: "#16a34a" },
              { label: "TEAM AVERAGE",  val: avgScore || "—", color: "#1D4ED8" },
              { label: "SESSIONS LOGGED", val: dashMode === "demo" ? "38" : dashMode === "live" ? realReps.reduce((a,r) => a + (r.sessions||0), 0) : "—", color: "#0f172a" },
            ].map((s, i) => (
              <div key={i} style={{ padding: "14px", borderRadius: 10, background: "#fff", border: "0.5px solid #D1D9E6", textAlign: "center" }}>
                <div style={{ fontSize: 24, fontWeight: 800, color: s.color, marginBottom: 3 }}>{s.val}</div>
                <div style={{ fontSize: 9, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.1em" }}>{s.label}</div>
              </div>
            ))}
          </div>
          {cisSorted.map((rep, i) => {
            const isDemo = dashMode === "demo"; const isPartial = dashMode === "partial"; const isMockish = isDemo || isPartial;
            const sc = isMockish ? rep.score : rep.cis_score;
            const c = scoreColor(sc);
            return (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 14, padding: "16px", borderRadius: 12, background: i === 0 ? c.bg : "#ffffff", border: `0.5px solid ${i === 0 ? c.border : "#e2e8f0"}`, marginBottom: 8, opacity: isDemo ? 0.7 : 1 }}>
                <div style={{ fontSize: 20, width: 28, textAlign: "center", flexShrink: 0 }}>{medals[i] || `#${i+1}`}</div>
                <div style={{ width: 34, height: 34, borderRadius: 9, background: c.bg, border: `1px solid ${c.border}`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, color: c.text, flexShrink: 0 }}>
                  {isDemo ? rep.name.split(" ").map(n => n[0]).join("") : rep.email?.slice(0, 2).toUpperCase()}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "#1e293b" }}>{isDemo ? rep.name : rep.email}</div>
                  <div style={{ fontSize: 11, color: "#94a3b8" }}>{isDemo ? `${rep.sessions} sessions` : isPartial ? "No sessions yet" : `Score: ${rep.cis_score}`}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 26, fontWeight: 800, color: c.text, filter: isPartial ? "blur(4px)" : "none" }}>{sc}</div>
                  {isMockish && !isPartial && <div style={{ fontSize: 11, fontWeight: 600, color: rep.trend?.startsWith("+") ? "#16a34a" : "#dc2626" }}>{rep.trend}</div>}
                </div>
                <div style={{ padding: "3px 9px", borderRadius: 20, background: c.bg, border: `1px solid ${c.border}`, fontSize: 10, fontWeight: 600, color: c.text, whiteSpace: "nowrap" }}>{c.label}</div>
              </div>
            );
          })}
        </div>
      )}

      {/* ── SALES IQ TAB ── */}
      {lbTab === "siq" && (
        <div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12, marginBottom: 20 }}>
            {[
              { label: "TOP IQ TODAY",  val: dashMode === "demo" ? mockSiqReps[0].score : "—", color: "#16a34a" },
              { label: "TESTS TAKEN",   val: dashMode === "demo" ? "4/5" : "—", color: "#1D4ED8" },
              { label: "AVG IQ SCORE",  val: dashMode === "demo" ? Math.round(mockSiqReps.reduce((a,r) => a+r.score, 0) / mockSiqReps.length) : "—", color: "#0f172a" },
            ].map((s, i) => (
              <div key={i} style={{ padding: "14px", borderRadius: 10, background: "#fff", border: "0.5px solid #D1D9E6", textAlign: "center" }}>
                <div style={{ fontSize: 24, fontWeight: 800, color: s.color, marginBottom: 3 }}>{s.val}</div>
                <div style={{ fontSize: 9, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.1em" }}>{s.label}</div>
              </div>
            ))}
          </div>
          {dashMode === "demo" ? mockSiqReps.map((rep, i) => {
            const c = scoreColor(rep.score);
            return (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 14, padding: "16px", borderRadius: 12, background: i === 0 ? c.bg : "#ffffff", border: `0.5px solid ${i === 0 ? c.border : "#e2e8f0"}`, marginBottom: 8, opacity: 0.7 }}>
                <div style={{ fontSize: 20, width: 28, textAlign: "center", flexShrink: 0 }}>{medals[i] || `#${i+1}`}</div>
                <div style={{ width: 34, height: 34, borderRadius: 9, background: c.bg, border: `1px solid ${c.border}`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, color: c.text, flexShrink: 0 }}>
                  {rep.name.split(" ").map(n => n[0]).join("")}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "#1e293b" }}>{rep.name}</div>
                  <div style={{ fontSize: 11, color: "#94a3b8" }}>{rep.role} · ✅ {rep.best} &nbsp;·&nbsp; 🎯 {rep.weak}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 26, fontWeight: 800, color: c.text }}>{rep.score}</div>
                  <div style={{ fontSize: 9, color: "#94a3b8" }}>today</div>
                </div>
                <div style={{ padding: "3px 9px", borderRadius: 20, background: c.bg, border: `1px solid ${c.border}`, fontSize: 10, fontWeight: 600, color: c.text, whiteSpace: "nowrap" }}>{c.label}</div>
              </div>
            );
          }) : (
            <div style={{ padding: "32px", borderRadius: 12, background: "#fff", border: "0.5px solid #D1D9E6", textAlign: "center", color: "#94A3B8", fontSize: 13 }}>
              Sales IQ rankings will appear once reps take the daily test.<br/>
              <span style={{ fontSize: 11 }}>Resets at midnight each day.</span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ─── Team Dashboard ────────────────────────────────────────────────────────────
function TeamDashboard({ teamView, setTeamView, onExit, currentUser, supabase }) {
  const [inviteEmail, setInviteEmail] = useState("");
  const [inviteStatus, setInviteStatus] = useState(null);
  const [inviteError, setInviteError] = useState("");
  const [editingObjection, setEditingObjection] = useState(null);
  const [teamData, setTeamData] = useState(null);
  const [members, setMembers] = useState([]);
  const [pendingInvites, setPendingInvites] = useState([]);
  const [loadingMembers, setLoadingMembers] = useState(true);
  const [recentlyAccepted, setRecentlyAccepted] = useState([]);
  const [teamName, setTeamName] = useState("My Team");
  const [editingTeamName, setEditingTeamName] = useState(false);
  const [teamNameInput, setTeamNameInput] = useState("");
  const [savingTeamName, setSavingTeamName] = useState(false);
  const [repNotes, setRepNotes] = useState({});
  const [editingNoteFor, setEditingNoteFor] = useState(null);
  const [noteInput, setNoteInput] = useState("");
  const [resendingInviteId, setResendingInviteId] = useState(null);
  const [resendSuccess, setResendSuccess] = useState(null);
  const [teamNotes, setTeamNotes] = useState("");
  const [savingTeamNotes, setSavingTeamNotes] = useState(false);
  const [teamNotesSaved, setTeamNotesSaved] = useState(false);
  const [removingId, setRemovingId] = useState(null);
  const [showHelp, setShowHelp] = useState(false);
  const [customPersonas, setCustomPersonas] = useState([]);
  const [showPersonaForm, setShowPersonaForm] = useState(false);
  const [newPersonaName, setNewPersonaName] = useState("");
  const [newPersonaDesc, setNewPersonaDesc] = useState("");
  const [newPersonaTags, setNewPersonaTags] = useState([]);
  const [savingPersona, setSavingPersona] = useState(false);
  const [deletingPersonaId, setDeletingPersonaId] = useState(null);
  const [copiedOnboarding, setCopiedOnboarding] = useState(false);
  const [useCustomOnboarding, setUseCustomOnboarding] = useState(false);
  const [customSessions, setCustomSessions] = useState([]);
  const [showSessionForm, setShowSessionForm] = useState(false);
  const [editingSessionId, setEditingSessionId] = useState(null);
  const [sessionForm, setSessionForm] = useState({ title: "", description: "", duration: "~30 min", video_url: "", resource_links: [] });
  const [newResourceLabel, setNewResourceLabel] = useState("");
  const [newResourceUrl, setNewResourceUrl] = useState("");
  const [savingSession, setSavingSession] = useState(false);
  const [deletingSessionId, setDeletingSessionId] = useState(null);
  const [customObjections, setCustomObjections] = useState([]);
  const [showObjectionForm, setShowObjectionForm] = useState(false);
  const [newObjCategory, setNewObjCategory] = useState("Price");
  const [newObjText, setNewObjText] = useState("");
  const [newObjResponse, setNewObjResponse] = useState("");
  const [savingObjection, setSavingObjection] = useState(false);
  const [deletingObjId, setDeletingObjId] = useState(null);
  const [editingCustomObj, setEditingCustomObj] = useState(null);
  const [editedObjResponse, setEditedObjResponse] = useState("");

  const OBJ_CATEGORIES = ["Price", "Timing", "Competition", "Trust", "Authority", "Need", "Other"];

  const loadCustomOnboarding = async () => {
    if (!teamData) return;
    const { data: setting } = await sbDB.select("team_onboarding", { team_id: teamData.id }, { single: true });
    if (setting) setUseCustomOnboarding(setting.use_custom);
    const { data: sessions } = await sbDB.select("team_onboarding_sessions", { team_id: teamData.id }, { order: "position.asc" });
    setCustomSessions(sessions || []);
  };

  useEffect(() => { if (teamData) loadCustomOnboarding(); }, [teamData]);

  const toggleCustomOnboarding = async (val) => {
    setUseCustomOnboarding(val);
    await sbDB.upsert("team_onboarding", { team_id: teamData.id, use_custom: val, updated_at: new Date().toISOString() }, { onConflict: "team_id" });
  };

  const handleSaveSession = async () => {
    if (!sessionForm.title.trim() || !sessionForm.description.trim() || !teamData) return;
    setSavingSession(true);
    if (editingSessionId) {
      await sbDB.update("team_onboarding_sessions", {
        title: sessionForm.title.trim(),
        description: sessionForm.description.trim(),
        duration: sessionForm.duration,
        video_url: sessionForm.video_url || null,
        resource_links: sessionForm.resource_links,
      }, { id: editingSessionId });
    } else {
      await sbDB.insert("team_onboarding_sessions", {
        team_id: teamData.id,
        position: customSessions.length,
        title: sessionForm.title.trim(),
        description: sessionForm.description.trim(),
        duration: sessionForm.duration,
        video_url: sessionForm.video_url || null,
        resource_links: sessionForm.resource_links,
      });
    }
    await loadCustomOnboarding();
    setShowSessionForm(false);
    setEditingSessionId(null);
    setSessionForm({ title: "", description: "", duration: "~30 min", video_url: "", resource_links: [] });
    setSavingSession(false);
  };

  const handleDeleteSession = async (id) => {
    if (!window.confirm("Remove this session?")) return;
    setDeletingSessionId(id);
    await sbDB.delete("team_onboarding_sessions", { id: id });
    await loadCustomOnboarding();
    setDeletingSessionId(null);
  };

  const handleMoveSession = async (id, direction) => {
    const idx = customSessions.findIndex(s => s.id === id);
    const newIdx = idx + direction;
    if (newIdx < 0 || newIdx >= customSessions.length) return;
    const updated = [...customSessions];
    [updated[idx], updated[newIdx]] = [updated[newIdx], updated[idx]];
    setCustomSessions(updated);
    await Promise.all(updated.map((s, i) => sbDB.update("team_onboarding_sessions", { position: i }, { id: s.id })));
  };

  const startEditSession = (session) => {
    setEditingSessionId(session.id);
    setSessionForm({ title: session.title, description: session.description, duration: session.duration, video_url: session.video_url || "", resource_links: session.resource_links || [] });
    setShowSessionForm(true);
  };

  const loadObjections = async () => {
    if (!teamData) return;
    const { data } = await sbDB.select("team_objections", { team_id: teamData.id }, { order: "created_at.asc" });
    setCustomObjections(data || []);
  };

  useEffect(() => { if (teamData) loadObjections(); }, [teamData]);

  const handleSaveObjection = async () => {
    if (!newObjText.trim() || !newObjResponse.trim() || !teamData) return;
    setSavingObjection(true);
    const { error } = await sbDB.insert("team_objections", {
      team_id: teamData.id,
      category: newObjCategory,
      objection: newObjText.trim(),
      response: newObjResponse.trim(),
    });
    if (!error) {
      await loadObjections();
      setNewObjText("");
      setNewObjResponse("");
      setNewObjCategory("Price");
      setShowObjectionForm(false);
    }
    setSavingObjection(false);
  };

  const handleSaveEditedObjection = async (id) => {
    await sbDB.update("team_objections", { response: editedObjResponse }, { id: id });
    await loadObjections();
    setEditingCustomObj(null);
  };

  const handleDeleteObjection = async (id) => {
    if (!window.confirm("Remove this objection?")) return;
    setDeletingObjId(id);
    await sbDB.delete("team_objections", { id: id });
    await loadObjections();
    setDeletingObjId(null);
  };

  const ONBOARDING_MODULES = [
    {
      num: "01", title: "Product & ICP", duration: "~30 min",
      desc: "The rep learns the product, ideal customer profile, key value propositions, and who they're selling to.",
      chips: [{ label: "Buyer Personas tab", color: "blue" }, { label: "Objection Library", color: "teal" }],
      copy: `Module 01 — Product & ICP (~30 min)\nBefore starting this module, head to the Buyer Personas tab to review your ICP, then open the Objection Library to familiarize yourself with the core value props you'll be defending.`,
    },
    {
      num: "02", title: "Discovery Mastery", duration: "~30 min",
      desc: "Focused entirely on asking questions. The rep practices open-ended discovery, active listening, and uncovering real pain.",
      chips: [{ label: "Full Roleplay", color: "purple" }, { label: "Buyer Personas tab", color: "blue" }],
      copy: `Module 02 — Discovery Mastery (~30 min)\nPull up the Buyer Personas tab and pick one persona to focus on. Then open Full Roleplay and run a discovery-only session — your only goal is asking questions, no pitching.`,
    },
    {
      num: "03", title: "Objection Handling", duration: "~45 min",
      desc: "Deep-dive on the ACRC framework. The rep drills the top 10 objections until responses are automatic.",
      chips: [{ label: "Objection Library", color: "teal" }, { label: "Full Roleplay", color: "purple" }],
      copy: `Module 03 — Objection Handling (~45 min)\nOpen the Objection Library and work through the top 10 objections listed there. Then jump into Full Roleplay and practice until your ACRC responses feel automatic.`,
    },
    {
      num: "04", title: "Full Roleplay", duration: "~45 min",
      desc: "End-to-end simulated sales call from cold intro through close.",
      chips: [{ label: "Full Roleplay", color: "purple" }, { label: "Leaderboard", color: "amber" }],
      copy: `Module 04 — Full Roleplay (~45 min)\nRun a complete end-to-end call in Full Roleplay — cold intro through close. After each session, check the Leaderboard to see how your scores compare to the team.`,
    },
    {
      num: "05", title: "Final Assessment", duration: "~30 min",
      desc: "Scored evaluation across all 7 Close Intelligence metrics. Rep receives a readiness score before their first call.",
      chips: [{ label: "Leaderboard", color: "amber" }, { label: "Dashboard", color: "coral" }],
      copy: `Module 05 — Final Assessment (~30 min)\nComplete your scored session in Full Roleplay. Your readiness score will appear on the Dashboard and your manager will be notified when you're ready for your first live call.`,
    },
  ];

  const ONBOARDING_MESSAGE = ONBOARDING_MODULES.map(m => m.copy).join("\n\n");

  const AVAILABLE_TAGS = ["Price", "Timing", "Trust", "Authority", "Competition", "Need", "Urgency"];

  const loadPersonas = async () => {
    if (!teamData) return;
    const { data } = await sbDB.select("team_personas", { team_id: teamData.id }, { order: "created_at.asc" });
    setCustomPersonas(data || []);
  };

  useEffect(() => { if (teamData) loadPersonas(); }, [teamData]);

  const handleSavePersona = async () => {
    if (!newPersonaName.trim() || !newPersonaDesc.trim() || !teamData) return;
    setSavingPersona(true);
    const { error } = await sbDB.insert("team_personas", {
      team_id: teamData.id,
      name: newPersonaName.trim(),
      description: newPersonaDesc.trim(),
      tags: newPersonaTags,
    });
    if (!error) {
      await loadPersonas();
      setNewPersonaName("");
      setNewPersonaDesc("");
      setNewPersonaTags([]);
      setShowPersonaForm(false);
    }
    setSavingPersona(false);
  };

  const handleDeletePersona = async (id) => {
    if (!window.confirm("Remove this persona?")) return;
    setDeletingPersonaId(id);
    await sbDB.delete("team_personas", { id: id });
    await loadPersonas();
    setDeletingPersonaId(null);
  };

  const loadTeam = async () => {
    if (!currentUser) return;
    setLoadingMembers(true);
    try {
      const { data: team, error: teamErr } = await sbDB.select("teams", { manager_id: currentUser.id }, { single: true });
      console.log("LOAD TEAM DEBUG:", { team, teamErr, userId: currentUser.id });
      if (team) {
        setTeamData(team);
        setTeamName(team.name || "My Team");
        setTeamNameInput(team.name || "My Team");
        if (team.notes) setTeamNotes(team.notes);

        const { data: memberData } = await sbDB.select("team_members", { team_id: team.id, status: "active" }, { order: "joined_at.asc" });
        setMembers(memberData || []);

        const notes = {};
        (memberData || []).forEach(m => { if (m.notes) notes[m.id] = m.notes; });
        setRepNotes(notes);

        const { data: inviteData } = await sbDB.select("team_invites", { team_id: team.id, status: "pending" }, { order: "created_at.desc" });
        setPendingInvites(inviteData || []);

        const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
        const { data: acceptedData } = await (async () => { const url = `${SUPABASE_URL}/rest/v1/team_invites?team_id=eq.${team.id}&status=eq.accepted&accepted_at=gte.${encodeURIComponent(sevenDaysAgo)}&order=accepted_at.desc`; const r = await fetch(url, { headers: { "apikey": SUPABASE_ANON_KEY, "Authorization": `Bearer ${SUPABASE_ANON_KEY}` } }); return { data: r.ok ? await r.json() : [] }; })();
        setRecentlyAccepted(acceptedData || []);
      }
    } catch (e) {
      console.error("Failed to load team:", e);
    }
    setLoadingMembers(false);
  };

  useEffect(() => { loadTeam(); }, [currentUser]);

  const handleInvite = async () => {
    if (!inviteEmail || !teamData) return;
    setInviteStatus("sending");
    setInviteError("");
    try {
      const res = await fetch(`${SUPABASE_URL}/functions/v1/team-invite`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Authorization": `Bearer ${SUPABASE_ANON_KEY}` },
        body: JSON.stringify({ inviteeEmail: inviteEmail.trim().toLowerCase(), teamId: teamData.id, managerName: currentUser?.email?.split("@")[0] || "Your manager" }),
      });
      const data = await res.json();
      if (res.ok && data.success) {
        setInviteStatus("sent");
        setInviteEmail("");
        await loadTeam();
        setTimeout(() => setInviteStatus(null), 3000);
      } else {
        setInviteStatus("error");
        setInviteError(data.error || "Something went wrong. Please try again.");
      }
    } catch (e) {
      setInviteStatus("error");
      setInviteError("Network error. Please try again.");
    }
  };

  const handleRemove = async (memberId, memberEmail) => {
    if (!window.confirm(`Remove ${memberEmail} from the team?`)) return;
    setRemovingId(memberId);
    await sbDB.update("team_members", { status: "inactive" }, { id: memberId });
    await loadTeam();
    setRemovingId(null);
  };

  const handleCancelInvite = async (inviteId) => {
    await sbDB.update("team_invites", { status: "expired" }, { id: inviteId });
    await loadTeam();
  };

  const handleSaveTeamName = async () => {
    if (!teamNameInput.trim() || !teamData) return;
    setSavingTeamName(true);
    await sbDB.update("teams", { name: teamNameInput.trim() }, { id: teamData.id });
    setTeamName(teamNameInput.trim());
    setEditingTeamName(false);
    setSavingTeamName(false);
  };

  const handleSaveNote = async (memberId) => {
    await sbDB.update("team_members", { notes: noteInput }, { id: memberId });
    setRepNotes(prev => ({ ...prev, [memberId]: noteInput }));
    setEditingNoteFor(null);
    setNoteInput("");
  };

  const handleResendInvite = async (invite) => {
    setResendingInviteId(invite.id);
    try {
      const res = await fetch(`${SUPABASE_URL}/functions/v1/team-invite`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Authorization": `Bearer ${SUPABASE_ANON_KEY}` },
        body: JSON.stringify({ inviteeEmail: invite.email, teamId: teamData.id, managerName: currentUser?.email?.split("@")[0] || "Your manager" }),
      });
      const data = await res.json();
      if (data.success) {
        setResendSuccess(invite.id);
        setTimeout(() => setResendSuccess(null), 3000);
      }
    } catch (e) { console.error("Resend error:", e); }
    setResendingInviteId(null);
  };

  const handleSaveTeamNotes = async () => {
    if (!teamData) return;
    setSavingTeamNotes(true);
    await sbDB.update("teams", { notes: teamNotes }, { id: teamData.id });
    setTeamNotesSaved(true);
    setTimeout(() => setTeamNotesSaved(false), 2500);
    setSavingTeamNotes(false);
  };

  const mockObjections = [
    { id: 1, category: "Price", objection: "Your price is too high.", response: "I completely understand — budget is always a factor. Can I ask, is it the total investment or the monthly payment that's the concern? [Listen] Got it. Most of our clients felt the same way initially, but once they saw the ROI over 90 days, it made complete sense. What would need to be true for this to feel worth it to you?" },
    { id: 2, category: "Timing", objection: "Now isn't a good time.", response: "That makes sense — timing is everything. Out of curiosity, what would need to change for the timing to feel right? [Listen] What I hear a lot is that when teams wait, the problem compounds. What's the cost of staying where you are for another 90 days?" },
    { id: 3, category: "Competition", objection: "We're looking at other options.", response: "That's smart — you should be comparing. What are the top things you're evaluating? [Listen] Here's where we're genuinely different: [differentiation]. Would it help to do a side-by-side comparison together?" },
    { id: 4, category: "Trust", objection: "I've never heard of you.", response: "Fair — we're selective about who we work with. Here's what I can tell you: [social proof]. Would a quick reference call with one of our clients help?" },
  ];

  const mockReps = [
    { name: "Jordan M.", score: 91, trend: "+4", sessions: 12, status: "active", tag: "Top Closer" },
    { name: "Aisha T.", score: 84, trend: "+7", sessions: 9, status: "active", tag: "Improving" },
    { name: "Carlos R.", score: 77, trend: "-2", sessions: 6, status: "active", tag: "Needs Work" },
    { name: "Priya S.", score: 73, trend: "+1", sessions: 8, status: "active", tag: "Needs Work" },
    { name: "Derek W.", score: 68, trend: "-5", sessions: 3, status: "inactive", tag: "At Risk" },
  ];

  const tagColor = (tag) => {
    if (tag === "Top Closer") return { bg: "#f0fdf4", color: "#16a34a", border: "#86efac" };
    if (tag === "Improving") return { bg: "#eff6ff", color: "#2563eb", border: "#93c5fd" };
    if (tag === "At Risk") return { bg: "#fef2f2", color: "#dc2626", border: "#fca5a5" };
    return { bg: "#fafafa", color: "#64748b", border: "#e2e8f0" };
  };

  const realReps = members.filter(m => m.role !== "admin");
  const hasRealReps = realReps.length > 0;
  const hasRealScores = realReps.some(m => m.cis_score != null);
  // mode: "demo" = no reps yet, "partial" = reps joined but no scores, "live" = real data
  const dashMode = !hasRealReps ? "demo" : !hasRealScores ? "partial" : "live";
  const usingMockData = dashMode === "demo";

  // For partial mode, blend real rep info with mock scores
  const partialReps = realReps.map((rep, i) => ({
    ...mockReps[i % mockReps.length],
    email: rep.email,
    joined_at: rep.joined_at,
    isPartial: true,
  }));

  const displayReps = dashMode === "demo" ? mockReps
    : dashMode === "partial" ? partialReps
    : realReps;

  const avgScore = dashMode === "live"
    ? (realReps.filter(r => r.cis_score).length
        ? Math.round(realReps.filter(r => r.cis_score).reduce((a, r) => a + r.cis_score, 0) / realReps.filter(r => r.cis_score).length)
        : 0)
    : Math.round(mockReps.reduce((a, r) => a + r.score, 0) / mockReps.length);
  const seatLimit = teamData?.seat_limit || 10;
  const seatsUsed = members.length;
  const seatsAvailable = seatLimit - seatsUsed;

  const navItems = [
    { id: "dashboard", label: "Dashboard", icon: "📊" },
    { id: "leaderboard", label: "Leaderboard", icon: "🏆" },
    { id: "members", label: "Members", icon: "👥" },
    { id: "library", label: "Objection Library", icon: "📚" },
    { id: "onboarding", label: "Rep Onboarding", icon: "🧑‍💼" },
    { id: "personas", label: "Buyer Personas", icon: "🎯" },
    { id: "report", label: "Team Notes", icon: "📝" },
  ];

  return (
    <div style={{ height: "var(--app-height, 100svh)", display: "flex", flexDirection: "column", background: "#E8EDF5", fontFamily: "'Inter', sans-serif", overflow: "hidden" }}>
      <style>{`
        .team-badge-pill { display: flex; }
        .team-seats-pill { display: flex; }
        .team-mgr-guide-label { display: inline; }
        .team-logo-text { display: block; }
        @media (max-width: 500px) {
          .team-badge-pill { display: none !important; }
          .team-seats-pill { display: none !important; }
          .team-mgr-guide-label { display: none !important; }
          .team-mgr-guide-btn { padding: 5px 8px !important; }
          .team-logo-text { display: none !important; }
        }
      `}</style>

      {/* Team Header */}
      <div style={{
        display: "flex", alignItems: "center", gap: 8,
        paddingLeft: 12, paddingRight: 12,
        paddingTop: "env(safe-area-inset-top)",
        height: "calc(48px + env(safe-area-inset-top))",
        background: "#ffffff", borderBottom: "1px solid #e2e8f0",
        boxShadow: "0 1px 3px rgba(0,0,0,0.04)", flexShrink: 0, zIndex: 20,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, flexShrink: 0 }}>
          <img src={BRAND_CONFIG.logoPath} alt={BRAND_CONFIG.appName} style={{ width: 30, height: 30, borderRadius: 7, objectFit: "cover", flexShrink: 0 }} />
          <div className="team-logo-text">
            <div style={{ fontSize: 12, fontWeight: 700, color: "#0f172a", letterSpacing: "0.04em", lineHeight: 1.1, whiteSpace: "nowrap" }}>{BRAND_CONFIG.appNameShort}</div>
            <div style={{ color: "#94a3b8", fontSize: 8, letterSpacing: "0.15em", whiteSpace: "nowrap" }}>MANAGER DASHBOARD</div>
          </div>
        </div>

        {/* Editable team name — single instance */}
        {editingTeamName ? (
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginLeft: 8 }}>
            <input
              value={teamNameInput}
              onChange={e => setTeamNameInput(e.target.value)}
              onKeyDown={e => { if (e.key === "Enter") handleSaveTeamName(); if (e.key === "Escape") setEditingTeamName(false); }}
              autoFocus
              style={{ padding: "4px 10px", borderRadius: 6, border: "1px solid #3b82f6", background: "#ffffff", fontSize: 12, fontWeight: 600, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none", width: 160 }}
            />
            <button onClick={handleSaveTeamName} disabled={savingTeamName} style={{ padding: "4px 10px", borderRadius: 6, background: "#3b82f6", border: "none", color: "#fff", fontSize: 11, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>{savingTeamName ? "..." : "Save"}</button>
            <button onClick={() => setEditingTeamName(false)} style={{ padding: "4px 8px", borderRadius: 6, background: "transparent", border: "1px solid #e2e8f0", color: "#64748b", fontSize: 11, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>✕</button>
          </div>
        ) : (
          <button onClick={() => { setEditingTeamName(true); setTeamNameInput(teamName); }} style={{ marginLeft: 8, padding: "4px 12px", borderRadius: 6, background: "#f1f5f9", border: "1px solid #e2e8f0", color: "#374151", fontSize: 12, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif", display: "flex", alignItems: "center", gap: 6 }}>
            {teamName} <span style={{ fontSize: 10, color: "#94a3b8" }}>✏️</span>
          </button>
        )}

        <div className="team-badge-pill" style={{ marginLeft: 4, alignItems: "center", gap: 6, padding: "3px 10px", borderRadius: 20, background: "#1e293b", border: "1px solid #334155" }}>
          <div style={{ width: 5, height: 5, borderRadius: "50%", background: "#86efac" }} />
          <span style={{ fontSize: 10, color: "#d1fae5", fontWeight: 600, letterSpacing: "0.06em" }}>TEAM</span>
        </div>
        <div className="team-seats-pill" style={{ marginLeft: 4, padding: "3px 10px", borderRadius: 20, background: "#f1f5f9", border: "1px solid #e2e8f0" }}>
          <span style={{ fontSize: 10, color: "#64748b", fontWeight: 600 }}>{seatsUsed}/{seatLimit} seats</span>
        </div>
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 6 }}>
          <button onClick={() => setShowHelp(true)} className="team-mgr-guide-btn" style={{
            background: "#f8fafc", border: "1px solid #e2e8f0",
            color: "#475569", borderRadius: 6, padding: "5px 12px",
            fontSize: 11, cursor: "pointer", fontFamily: "'Inter', sans-serif",
            display: "flex", alignItems: "center", gap: 5, fontWeight: 600,
          }}><span>📖</span><span className="team-mgr-guide-label">Manager Guide</span></button>
          <button onClick={onExit} style={{
            background: "#1e293b", border: "1px solid #334155",
            color: "#fff", borderRadius: 6, padding: "5px 14px",
            fontSize: 11, cursor: "pointer", fontFamily: "'Inter', sans-serif",
            fontWeight: 600, whiteSpace: "nowrap", flexShrink: 0,
          }}>← Chat</button>
        </div>
      </div>

      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
        {/* Tab Bar */}
        <div style={{
          display: "flex", alignItems: "center", gap: 2,
          padding: "0 24px", background: "#ffffff",
          borderBottom: "1px solid #e2e8f0", flexShrink: 0,
          overflowX: "auto",
        }}>
          {navItems.map(n => (
            <button key={n.id} onClick={() => setTeamView(n.id)} style={{
              padding: "12px 16px", border: "none", background: "transparent",
              borderBottom: teamView === n.id ? "2px solid #1D4ED8" : "2px solid transparent",
              color: teamView === n.id ? "#1D4ED8" : "#64748b",
              cursor: "pointer", fontSize: 12.5, fontWeight: teamView === n.id ? 600 : 400,
              display: "flex", alignItems: "center", gap: 6, transition: "all 0.15s",
              fontFamily: "'Inter', sans-serif", whiteSpace: "nowrap", flexShrink: 0,
            }}>
              <span>{n.icon}</span>{n.label}
              {n.id === "members" && pendingInvites.length > 0 && (
                <span style={{ background: "#3b82f6", color: "#fff", borderRadius: 10, fontSize: 9, padding: "1px 5px", fontWeight: 700 }}>{pendingInvites.length}</span>
              )}
            </button>
          ))}
        </div>

        {/* Main content */}
        <div style={{ flex: 1, overflowY: "auto", padding: "28px 32px", background: "#E8EDF5" }}>

          {/* DASHBOARD */}
          {teamView === "dashboard" && (
            <div style={{ maxWidth: 860 }}>
              <div style={{ marginBottom: 24 }}>
                <div style={{ fontSize: 20, fontWeight: 700, color: "#0f172a", marginBottom: 4 }}>Team Overview</div>
                <div style={{ fontSize: 13, color: "#64748b" }}>Performance stats update after each rep session.</div>
              </div>

              {dashMode === "demo" && (
                <div style={{ background: "#fff", border: "0.5px solid #D1D9E6", borderRadius: 12, padding: 20, marginBottom: 20 }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
                    <div style={{ fontSize: 15, fontWeight: 700, color: "#0F172A" }}>👋 Welcome to your Team Dashboard</div>
                    <div style={{ background: "#DBEAFE", color: "#1D4ED8", fontSize: 11, fontWeight: 600, padding: "3px 10px", borderRadius: 20 }}>Sample preview</div>
                  </div>
                  <div style={{ fontSize: 13, color: "#64748B", marginBottom: 16, lineHeight: 1.6 }}>You're all set. Here's how to get your team up and running in 3 steps.</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    {[
                      { step: "1", title: "Invite your first rep", desc: "Go to the Members tab and enter their email. They'll get an invite link instantly.", action: "Go to Members →", tab: "members" },
                      { step: "2", title: "Have them complete their first session", desc: "Send them the onboarding instructions from the Rep Onboarding tab. They start in the chat.", action: "View Onboarding →", tab: "onboarding" },
                      { step: "3", title: "Come back here to see real stats", desc: "Once they've completed a session, their score and progress will replace this sample data.", action: null, tab: null },
                    ].map((s, i) => (
                      <div key={i} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 16px", borderRadius: 10, background: "#F8FAFC", border: "0.5px solid #E2E8F0" }}>
                        <div style={{ width: 28, height: 28, borderRadius: 8, background: "#1D4ED8", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 700, color: "#fff", flexShrink: 0 }}>{s.step}</div>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: 13, fontWeight: 600, color: "#0F172A", marginBottom: 2 }}>{s.title}</div>
                          <div style={{ fontSize: 12, color: "#94A3B8", lineHeight: 1.5 }}>{s.desc}</div>
                        </div>
                        {s.action && (
                          <button onClick={() => setTeamView(s.tab)} style={{ padding: "6px 14px", borderRadius: 8, background: "#fff", border: "0.5px solid #D1D9E6", color: "#1D4ED8", fontSize: 12, fontWeight: 500, cursor: "pointer", fontFamily: "'Inter', sans-serif", whiteSpace: "nowrap" }}>{s.action}</button>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {dashMode === "partial" && (
                <div style={{ padding: "16px 20px", borderRadius: 12, background: "#EFF6FF", border: "0.5px solid #BFDBFE", marginBottom: 24, display: "flex", alignItems: "center", gap: 14 }}>
                  <span style={{ fontSize: 20, flexShrink: 0 }}>⏳</span>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 700, color: "#1E3A8A", marginBottom: 2 }}>Your reps have joined — waiting for first sessions</div>
                    <div style={{ fontSize: 12, color: "#1D4ED8", lineHeight: 1.5 }}>Scores and progress will appear here once your reps complete their first training session. Names are real, scores are sample previews.</div>
                  </div>
                  <button onClick={() => setTeamView("onboarding")} style={{ padding: "6px 14px", borderRadius: 8, background: "#1D4ED8", border: "none", color: "#fff", fontSize: 11, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif", whiteSpace: "nowrap", flexShrink: 0 }}>Send Onboarding →</button>
                </div>
              )}

              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 20 }}>
                {[
                  { label: "Sessions This Week", value: dashMode === "live" ? "—" : "31", sub: dashMode === "live" ? "tracking coming soon" : "sample preview" },
                  { label: "Avg CIS Score", value: dashMode === "demo" ? `${avgScore}` : dashMode === "partial" ? "—" : `${avgScore || "—"}`, sub: dashMode === "demo" ? "sample preview" : dashMode === "partial" ? "after first sessions" : "across active reps" },
                  { label: "Active Members", value: `${seatsUsed}/${seatLimit}`, sub: `${seatsAvailable} seats available` },
                  { label: "Pending Invites", value: `${pendingInvites.length}`, sub: "awaiting acceptance" },
                ].map((s, i) => (
                  <div key={i} style={{ padding: "16px", borderRadius: 12, background: "#ffffff", border: "0.5px solid #D1D9E6" }}>
                    <div style={{ fontSize: 24, fontWeight: 700, color: "#1e293b", marginBottom: 4 }}>{s.value}</div>
                    <div style={{ fontSize: 11, fontWeight: 600, color: "#374151", marginBottom: 2 }}>{s.label}</div>
                    <div style={{ fontSize: 10, color: "#94a3b8" }}>{s.sub}</div>
                  </div>
                ))}
              </div>

              {/* Expanded KPI row */}
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 28 }}>
                {(() => {
                  const topRep = dashMode === "live"
                    ? (realReps.filter(r => r.cis_score).sort((a,b) => b.cis_score - a.cis_score)[0] || null)
                    : { name: "Jordan M.", score: 91 };
                  const topRepName = dashMode === "live" ? (topRep?.email?.split("@")[0] || "—") : topRep?.name;
                  const topRepScore = dashMode === "live" ? (topRep?.cis_score || "—") : topRep?.score;

                  const weekAvg = dashMode === "demo" ? avgScore : dashMode === "partial" ? null : avgScore;
                  const prevWeekAvg = dashMode === "demo" ? avgScore - 4 : null;
                  const improvement = (weekAvg && prevWeekAvg) ? `+${weekAvg - prevWeekAvg} pts` : dashMode === "demo" ? "+4.2 pts" : "—";

                  const skillTotals = {};
                  const skillCounts = {};
                  (dashMode === "demo" ? [
                    { skills: { Discovery: 84, Objection: 78, Closing: 91, Prospecting: 62, Negotiation: 71 } },
                    { skills: { Discovery: 79, Objection: 85, Closing: 82, Prospecting: 68, Negotiation: 74 } },
                    { skills: { Discovery: 65, Objection: 63, Closing: 77, Prospecting: 55, Negotiation: 60 } },
                  ] : []).forEach(r => {
                    Object.entries(r.skills || {}).forEach(([k,v]) => {
                      skillTotals[k] = (skillTotals[k]||0) + v;
                      skillCounts[k] = (skillCounts[k]||0) + 1;
                    });
                  });
                  const weakSkillName = Object.keys(skillTotals).length
                    ? Object.entries(skillTotals).sort((a,b) => (a[1]/skillCounts[a[0]]) - (b[1]/skillCounts[b[0]]))[0]?.[0]
                    : "Prospecting";
                  const weakSkillAvg = weakSkillName && skillCounts[weakSkillName]
                    ? Math.round(skillTotals[weakSkillName] / skillCounts[weakSkillName])
                    : dashMode === "demo" ? 62 : null;

                  return [
                    {
                      label: "Top Scorer This Week", icon: "🏆",
                      value: topRepScore !== "—" ? topRepScore : "—",
                      sub: topRepScore !== "—" ? topRepName : "No scores yet",
                      accent: topRepScore !== "—" ? scoreColor(topRepScore).text : "#94a3b8",
                    },
                    {
                      label: "Sessions Today", icon: "⚡",
                      value: dashMode === "live" ? "—" : "8",
                      sub: dashMode === "live" ? "tracking coming soon" : "sample preview",
                      accent: "#1D4ED8",
                    },
                    {
                      label: "Week-over-Week", icon: "📈",
                      value: improvement,
                      sub: "avg CIS improvement",
                      accent: "#16a34a",
                    },
                    {
                      label: "Weakest Team Skill", icon: "🎯",
                      value: weakSkillName,
                      sub: weakSkillAvg ? `avg ${weakSkillAvg} — drill this in your next meeting` : "after first sessions",
                      accent: weakSkillAvg ? scoreColor(weakSkillAvg).text : "#94a3b8",
                    },
                  ];
                })().map((s, i) => (
                  <div key={i} style={{ padding: "16px", borderRadius: 12, background: "#ffffff", border: "0.5px solid #D1D9E6" }}>
                    <div style={{ fontSize: 13, marginBottom: 8 }}>{s.icon}</div>
                    <div style={{ fontSize: i === 3 ? 15 : 22, fontWeight: 700, color: s.accent, marginBottom: 4, lineHeight: 1.1 }}>{s.value}</div>
                    <div style={{ fontSize: 11, fontWeight: 600, color: "#374151", marginBottom: 2 }}>{s.label}</div>
                    <div style={{ fontSize: 10, color: "#94a3b8", lineHeight: 1.4 }}>{s.sub}</div>
                  </div>
                ))}
              </div>

              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: "#94A3B8", letterSpacing: "0.15em" }}>REP PERFORMANCE</div>
                {dashMode !== "live" && <div style={{ fontSize: 10, color: "#1D4ED8", background: "#DBEAFE", border: "0.5px solid #BFDBFE", padding: "3px 9px", borderRadius: 20, fontWeight: 600 }}>{dashMode === "demo" ? "Sample data" : "Preview scores"}</div>}
              </div>

              {/* Team Sales IQ Preview */}
              <div style={{ marginTop: 24, marginBottom: 24 }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: "#94A3B8", letterSpacing: "0.15em" }}>⚡ TEAM SALES IQ · TODAY</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <div style={{ background: "#DBEAFE", color: "#1D4ED8", fontSize: 10, fontWeight: 600, padding: "2px 8px", borderRadius: 10 }}>NEW</div>
                    <div style={{ fontSize: 12, color: "#64748B", cursor: "pointer" }}>See all Sales IQ results →</div>
                  </div>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {(dashMode === "demo" ? [
                    { name: "Jordan M.", sub: "Done today", best: "Closing", bestScore: 95, weak: "Prospecting", weakScore: 68, score: 94, tag: "Elite" },
                    { name: "Aisha T.", sub: "Done today", best: "Closing", bestScore: 85, weak: "Prospecting", weakScore: 62, score: 82, tag: "Strong" },
                    { name: "Carlos R.", sub: "Done today", best: "Discovery", bestScore: 70, weak: "Negotiation", weakScore: 48, score: 63, tag: "Developing" },
                  ] : []).map((rep, i) => {
                    const tagStyle = rep.tag === "Elite" ? { bg: "#EFF6FF", color: "#1D4ED8", border: "#BFDBFE" } : rep.tag === "Strong" ? { bg: "#F0FDF4", color: "#16A34A", border: "#BBF7D0" } : { bg: "#F8FAFC", color: "#64748B", border: "#E2E8F0" };
                    return (
                      <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 16px", borderRadius: 12, background: "#fff", border: "0.5px solid #D1D9E6" }}>
                        <div style={{ width: 34, height: 34, borderRadius: 8, background: "#EFF6FF", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 700, color: "#1D4ED8", flexShrink: 0 }}>{rep.name.split(" ").map(n => n[0]).join("")}</div>
                        <div style={{ flexShrink: 0, width: 76 }}>
                          <div style={{ fontSize: 13, fontWeight: 500, color: "#0F172A", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{rep.name}</div>
                          <div style={{ fontSize: 11, color: "#94A3B8", marginTop: 1 }}>{rep.sub}</div>
                        </div>
                        <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 3, minWidth: 0, maxWidth: 140, overflow: "hidden" }}>
                          <div style={{ fontSize: 11, display: "flex", alignItems: "center", gap: 3 }}>
                            <span style={{ flexShrink: 0 }}>🔼</span>
                            <span style={{ color: "#475569", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1 }}>{rep.best}</span>
                            <span style={{ fontWeight: 700, color: "#1D4ED8", flexShrink: 0, marginLeft: 3 }}>{rep.bestScore}</span>
                          </div>
                          <div style={{ fontSize: 11, display: "flex", alignItems: "center", gap: 3 }}>
                            <span style={{ flexShrink: 0 }}>🔽</span>
                            <span style={{ color: "#475569", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1 }}>{rep.weak}</span>
                            <span style={{ fontWeight: 700, color: "#94A3B8", flexShrink: 0, marginLeft: 3 }}>{rep.weakScore}</span>
                          </div>
                        </div>
                        <div style={{ flexShrink: 0, width: 38, textAlign: "center", marginLeft: "auto" }}>
                          <div style={{ fontSize: 22, fontWeight: 700, color: scoreColor(rep.score).text, lineHeight: 1 }}>{rep.score}</div>
                          <div style={{ fontSize: 9, color: "#94A3B8" }}>/100</div>
                        </div>
                        <div style={{ fontSize: 11, fontWeight: 600, padding: "3px 8px", borderRadius: 20, background: tagStyle.bg, color: tagStyle.color, border: `0.5px solid ${tagStyle.border}`, whiteSpace: "nowrap", flexShrink: 0 }}>{rep.tag}</div>
                      </div>
                    );
                  })}
                  {dashMode !== "demo" && (
                    <div style={{ padding: "16px", borderRadius: 12, background: "#fff", border: "0.5px solid #D1D9E6", textAlign: "center", color: "#94A3B8", fontSize: 13 }}>Sales IQ data will appear once reps start taking the daily test.</div>
                  )}
                </div>
              </div>

              {/* CIS Leaderboard */}
              <div style={{ borderTop: "0.5px solid #D1D9E6", paddingTop: 20, marginTop: 4 }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: "#94A3B8", letterSpacing: "0.15em" }}>📊 CIS LEADERBOARD · ALL TIME</div>
                  <div style={{ fontSize: 10, color: "#64748B" }}>Close Intelligence Score</div>
                </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {dashMode === "live" ? realReps.map((rep, i) => (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 16px", borderRadius: 12, background: "#ffffff", border: "0.5px solid #D1D9E6" }}>
                    <div style={{ width: 32, height: 32, borderRadius: 8, background: "#f1f5f9", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, color: "#4b5563", flexShrink: 0 }}>{rep.email.slice(0, 2).toUpperCase()}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: "#1e293b" }}>{rep.email}</div>
                      <div style={{ fontSize: 11, color: "#94a3b8" }}>Joined {new Date(rep.joined_at).toLocaleDateString()}</div>
                    </div>
                    <div style={{ fontSize: 20, fontWeight: 700, color: rep.cis_score ? scoreColor(rep.cis_score).text : "#94a3b8" }}>{rep.cis_score || "—"}</div>
                    <div style={{ padding: "3px 9px", borderRadius: 20, background: rep.cis_score ? scoreColor(rep.cis_score).bg : "#f1f5f9", border: `1px solid ${rep.cis_score ? scoreColor(rep.cis_score).border : "#e2e8f0"}`, fontSize: 10, fontWeight: 600, color: rep.cis_score ? scoreColor(rep.cis_score).text : "#94a3b8" }}>{rep.cis_score ? scoreColor(rep.cis_score).label : "No data yet"}</div>
                  </div>
                )) : displayReps.map((rep, i) => {
                  const tc = tagColor(rep.tag);
                  const isPartialMode = dashMode === "partial";
                  return (
                    <div key={i} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 16px", borderRadius: 12, background: "#ffffff", border: "0.5px solid #D1D9E6", opacity: isPartialMode ? 0.85 : 0.6, position: "relative" }}>
                      <div style={{ width: 32, height: 32, borderRadius: 8, background: "#f1f5f9", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, color: "#4b5563", flexShrink: 0 }}>
                        {isPartialMode ? rep.email.slice(0, 2).toUpperCase() : rep.name.split(" ").map(n => n[0]).join("")}
                      </div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: "#1e293b" }}>{isPartialMode ? rep.email : rep.name}</div>
                        <div style={{ fontSize: 11, color: "#94a3b8" }}>{isPartialMode ? "No sessions yet" : `${rep.sessions} sessions`}</div>
                      </div>
                      <div style={{ fontSize: 20, fontWeight: 700, color: scoreColor(rep.score).text, filter: isPartialMode ? "blur(4px)" : "none", userSelect: isPartialMode ? "none" : "auto" }}>{rep.score}</div>
                      <div style={{ fontSize: 12, fontWeight: 600, color: rep.trend?.startsWith("+") ? "#16a34a" : "#dc2626", width: 32, filter: isPartialMode ? "blur(4px)" : "none" }}>{rep.trend}</div>
                      <div style={{ padding: "3px 9px", borderRadius: 20, background: isPartialMode ? "#f1f5f9" : tc.bg, border: `1px solid ${isPartialMode ? "#e2e8f0" : tc.border}`, fontSize: 10, fontWeight: 600, color: isPartialMode ? "#94a3b8" : tc.color }}>{isPartialMode ? "Awaiting session" : rep.tag}</div>
                    </div>
                  );
                })}
              </div>
              </div>

              {/* ── SKILL HEAT MAP ── */}
              <div style={{ background: "#ffffff", border: "0.5px solid #D1D9E6", borderRadius: 12, padding: "20px", marginTop: 24, marginBottom: 24 }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: "#94A3B8", letterSpacing: "0.15em" }}>🗺 SKILL HEAT MAP · TEAM AVERAGE</div>
                  <div style={{ fontSize: 10, color: "#64748B" }}>Color = score tier · Click a cell to drill</div>
                </div>
                {(() => {
                  const skills = ["Discovery", "Objection Handling", "Closing", "Prospecting", "Negotiation"];
                  const demoData = dashMode === "demo" ? [
                    { name: "Jordan M.", scores: [84, 91, 95, 72, 88] },
                    { name: "Aisha T.",  scores: [79, 85, 82, 68, 74] },
                    { name: "Carlos R.", scores: [65, 63, 77, 55, 60] },
                    { name: "Priya S.",  scores: [73, 76, 80, 61, 70] },
                    { name: "Derek W.",  scores: [58, 61, 68, 49, 55] },
                  ] : [];
                  if (dashMode !== "demo") return (
                    <div style={{ textAlign: "center", color: "#94a3b8", fontSize: 13, padding: "20px 0" }}>Heat map will populate after reps complete sessions.</div>
                  );
                  return (
                    <div style={{ overflowX: "auto" }}>
                      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 11 }}>
                        <thead>
                          <tr>
                            <th style={{ textAlign: "left", padding: "6px 10px", color: "#94a3b8", fontWeight: 600, fontSize: 10, letterSpacing: "0.06em" }}>REP</th>
                            {skills.map(s => <th key={s} style={{ padding: "6px 8px", color: "#94a3b8", fontWeight: 600, fontSize: 10, textAlign: "center", letterSpacing: "0.04em" }}>{s}</th>)}
                          </tr>
                        </thead>
                        <tbody>
                          {demoData.map((rep, ri) => (
                            <tr key={ri}>
                              <td style={{ padding: "6px 10px", fontWeight: 600, color: "#374151", fontSize: 12, whiteSpace: "nowrap" }}>{rep.name}</td>
                              {rep.scores.map((sc, si) => {
                                const c = scoreColor(sc);
                                return (
                                  <td key={si} style={{ padding: "4px" }}>
                                    <div style={{ background: c.bg, border: `1px solid ${c.border}`, borderRadius: 6, padding: "6px 4px", textAlign: "center", minWidth: 42 }}>
                                      <div style={{ fontSize: 13, fontWeight: 700, color: c.text }}>{sc}</div>
                                    </div>
                                  </td>
                                );
                              })}
                            </tr>
                          ))}
                          {/* Team avg row */}
                          <tr style={{ borderTop: "1px solid #E2E8F0" }}>
                            <td style={{ padding: "8px 10px", fontWeight: 700, color: "#0f172a", fontSize: 11, letterSpacing: "0.06em" }}>TEAM AVG</td>
                            {[0,1,2,3,4].map(si => {
                              const avg = Math.round(demoData.reduce((a,r) => a + r.scores[si], 0) / demoData.length);
                              const c = scoreColor(avg);
                              return (
                                <td key={si} style={{ padding: "4px" }}>
                                  <div style={{ background: c.bg, border: `1px solid ${c.border}`, borderRadius: 6, padding: "6px 4px", textAlign: "center", minWidth: 42 }}>
                                    <div style={{ fontSize: 13, fontWeight: 800, color: c.text }}>{avg}</div>
                                  </div>
                                </td>
                              );
                            })}
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  );
                })()}
              </div>

              {/* ── WEEKLY ACTIVITY TREND + REP SPOTLIGHT ── */}
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 24 }}>

                {/* Weekly Trend */}
                <div style={{ background: "#ffffff", border: "0.5px solid #D1D9E6", borderRadius: 12, padding: "20px" }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: "#94A3B8", letterSpacing: "0.15em", marginBottom: 16 }}>📅 WEEKLY ACTIVITY TREND</div>
                  {(() => {
                    const days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
                    const counts = dashMode === "demo" ? [4,7,6,8,5,2,3] : [0,0,0,0,0,0,0];
                    const maxVal = Math.max(...counts, 1);
                    return (
                      <div style={{ display: "flex", alignItems: "flex-end", gap: 6, height: 64 }}>
                        {days.map((d, i) => (
                          <div key={d} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                            <div style={{ fontSize: 10, fontWeight: 600, color: "#374151" }}>{counts[i] || ""}</div>
                            <div style={{ width: "100%", borderRadius: 4, background: counts[i] > 0 ? "#1D4ED8" : "#E2E8F0", height: `${Math.max(6, (counts[i]/maxVal)*44)}px`, opacity: i === 6 ? 0.5 : 1 }} />
                            <div style={{ fontSize: 9, color: "#94a3b8" }}>{d}</div>
                          </div>
                        ))}
                      </div>
                    );
                  })()}
                  {dashMode !== "demo" && <div style={{ fontSize: 11, color: "#94a3b8", textAlign: "center", marginTop: 12 }}>Activity will appear after first sessions.</div>}
                </div>

                {/* Rep Spotlight */}
                <div style={{ background: "#ffffff", border: "0.5px solid #D1D9E6", borderRadius: 12, padding: "20px" }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: "#94A3B8", letterSpacing: "0.15em", marginBottom: 14 }}>🔦 REP SPOTLIGHT</div>
                  {dashMode === "demo" ? (
                    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                      {/* Most Improved */}
                      <div style={{ padding: "12px 14px", borderRadius: 10, background: "#F0FDF4", border: "0.5px solid #BBF7D0" }}>
                        <div style={{ fontSize: 9, fontWeight: 700, color: "#16a34a", letterSpacing: "0.1em", marginBottom: 6 }}>🚀 MOST IMPROVED THIS WEEK</div>
                        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                          <div>
                            <div style={{ fontSize: 13, fontWeight: 700, color: "#0f172a" }}>Aisha T.</div>
                            <div style={{ fontSize: 11, color: "#64748b" }}>+7 pts from last week · 9 sessions</div>
                          </div>
                          <div style={{ fontSize: 22, fontWeight: 800, color: "#16a34a" }}>84</div>
                        </div>
                      </div>
                      {/* At Risk */}
                      <div style={{ padding: "12px 14px", borderRadius: 10, background: "#FEF2F2", border: "0.5px solid #FECACA" }}>
                        <div style={{ fontSize: 9, fontWeight: 700, color: "#dc2626", letterSpacing: "0.1em", marginBottom: 6 }}>⚠️ NEEDS ATTENTION</div>
                        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                          <div>
                            <div style={{ fontSize: 13, fontWeight: 700, color: "#0f172a" }}>Derek W.</div>
                            <div style={{ fontSize: 11, color: "#64748b" }}>-5 pts · 3 sessions · no activity in 4 days</div>
                          </div>
                          <div style={{ fontSize: 22, fontWeight: 800, color: "#dc2626" }}>68</div>
                        </div>
                      </div>
                    </div>
                  ) : (
                    <div style={{ textAlign: "center", color: "#94a3b8", fontSize: 13, paddingTop: 16 }}>Spotlight appears after reps complete sessions.</div>
                  )}
                </div>
              </div>

            </div>
          )}

          {/* LEADERBOARD */}
          {teamView === "leaderboard" && (
            <TeamLeaderboard
              dashMode={dashMode}
              mockReps={mockReps}
              partialReps={partialReps}
              realReps={realReps}
              avgScore={avgScore}
            />
          )}

          {/* MEMBERS */}
          {teamView === "members" && (
            <div style={{ maxWidth: 640 }}>
              <div style={{ marginBottom: 24 }}>
                <div style={{ fontSize: 20, fontWeight: 700, color: "#0f172a", marginBottom: 4 }}>Team Members</div>
                <div style={{ fontSize: 13, color: "#64748b" }}>
                  {seatsUsed} of {seatLimit} seats used
                  {seatsAvailable === 0
                    ? <span style={{ color: "#dc2626", fontWeight: 600 }}> · Seat limit reached</span>
                    : <span style={{ color: "#16a34a", fontWeight: 600 }}> · {seatsAvailable} available</span>
                  }
                </div>
              </div>

              <div style={{ padding: "18px", borderRadius: 12, background: "#ffffff", border: "1px solid #e2e8f0", marginBottom: 24 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: "#374151", marginBottom: 4 }}>Invite a Team Member</div>
                <div style={{ fontSize: 11, color: "#94a3b8", marginBottom: 12 }}>They'll receive an email with a link to join your team. Paid access unlocks automatically after billing is confirmed.</div>
                <div style={{ display: "flex", gap: 8 }}>
                  <input
                    value={inviteEmail}
                    onChange={e => setInviteEmail(e.target.value)}
                    onKeyDown={e => e.key === "Enter" && handleInvite()}
                    placeholder="colleague@company.com"
                    disabled={seatsAvailable <= 0 || inviteStatus === "sending"}
                    style={{ flex: 1, padding: "9px 12px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#f8fafc", fontSize: 13, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none" }}
                  />
                  <button onClick={handleInvite} disabled={!inviteEmail || seatsAvailable <= 0 || inviteStatus === "sending"} style={{
                    padding: "9px 18px", borderRadius: 8,
                    background: (!inviteEmail || seatsAvailable <= 0) ? "#e2e8f0" : "#1e293b",
                    border: "none", color: (!inviteEmail || seatsAvailable <= 0) ? "#94a3b8" : "#fff",
                    fontSize: 12, fontWeight: 600, cursor: (!inviteEmail || seatsAvailable <= 0) ? "not-allowed" : "pointer",
                    fontFamily: "'Inter', sans-serif",
                  }}>{inviteStatus === "sending" ? "Sending..." : "Send Invite"}</button>
                </div>
                {inviteStatus === "sent" && <div style={{ fontSize: 12, color: "#16a34a", marginTop: 8 }}>✓ Invite sent!</div>}
                {inviteStatus === "error" && <div style={{ fontSize: 12, color: "#dc2626", marginTop: 8 }}>⚠ {inviteError}</div>}
              </div>

              {(pendingInvites.length > 0 || recentlyAccepted.length > 0) && (
                <div style={{ marginBottom: 24 }}>
                  {recentlyAccepted.length > 0 && (
                    <div style={{ marginBottom: 16 }}>
                      <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 12 }}>RECENTLY JOINED</div>
                      {recentlyAccepted.map((inv, i) => (
                        <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 16px", borderRadius: 10, background: "#f0fdf4", border: "1px solid #86efac", marginBottom: 8 }}>
                          <div style={{ width: 32, height: 32, borderRadius: 7, background: "#dcfce7", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14 }}>✅</div>
                          <div style={{ flex: 1 }}>
                            <div style={{ fontSize: 13, fontWeight: 600, color: "#1e293b" }}>{inv.email}</div>
                            <div style={{ fontSize: 11, color: "#16a34a" }}>Accepted · joined {new Date(inv.accepted_at).toLocaleDateString()}</div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                  {pendingInvites.length > 0 && (
                    <div>
                      <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 12 }}>PENDING INVITES ({pendingInvites.length})</div>
                      {pendingInvites.map((inv, i) => (
                        <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 16px", borderRadius: 10, background: "#fffbeb", border: "1px solid #fde68a", marginBottom: 8 }}>
                          <div style={{ width: 32, height: 32, borderRadius: 7, background: "#fef3c7", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14 }}>✉️</div>
                          <div style={{ flex: 1 }}>
                            <div style={{ fontSize: 13, fontWeight: 600, color: "#1e293b" }}>{inv.email}</div>
                            <div style={{ fontSize: 11, color: "#94a3b8" }}>Pending · sent {new Date(inv.created_at).toLocaleDateString()}</div>
                          </div>
                          <button onClick={() => handleResendInvite(inv)} disabled={resendingInviteId === inv.id} style={{ padding: "3px 10px", borderRadius: 6, background: resendSuccess === inv.id ? "#f0fdf4" : "#f8fafc", border: `1px solid ${resendSuccess === inv.id ? "#86efac" : "#e2e8f0"}`, color: resendSuccess === inv.id ? "#16a34a" : "#64748b", fontSize: 10, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>{resendingInviteId === inv.id ? "..." : resendSuccess === inv.id ? "✓ Sent!" : "Resend"}</button>
                          <button onClick={() => handleCancelInvite(inv.id)} style={{ background: "none", border: "none", color: "#cbd5e1", cursor: "pointer", fontSize: 16, padding: "0 4px" }}>×</button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}

              <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 12 }}>ACTIVE MEMBERS ({members.length})</div>
              {loadingMembers ? (
                <div style={{ textAlign: "center", padding: 40, color: "#94a3b8", fontSize: 13 }}>Loading members...</div>
              ) : members.length === 0 ? (
                <div style={{ textAlign: "center", padding: 40, color: "#94a3b8", fontSize: 13, background: "#ffffff", borderRadius: 12, border: "1px solid #e2e8f0" }}>No active members yet.</div>
              ) : (
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {members.map((m, i) => {
                    const isManager = m.user_id === currentUser?.id;
                    return (
                      <div key={i} style={{ borderRadius: 10, background: "#ffffff", border: "1px solid #e2e8f0" }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 16px" }}>
                          <div style={{ width: 32, height: 32, borderRadius: 7, background: isManager ? "#1e293b" : "#f1f5f9", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, color: isManager ? "#fff" : "#4b5563" }}>
                            {m.email.slice(0, 2).toUpperCase()}
                          </div>
                          <div style={{ flex: 1 }}>
                            <div style={{ fontSize: 13, fontWeight: 600, color: "#1e293b" }}>{isManager ? "You" : m.email}</div>
                            <div style={{ fontSize: 11, color: "#94a3b8" }}>{isManager ? currentUser.email : `Joined ${new Date(m.joined_at).toLocaleDateString()}`}</div>
                          </div>
                          <div style={{ padding: "3px 9px", borderRadius: 20, background: isManager ? "#1e293b" : "#f1f5f9", fontSize: 10, fontWeight: 600, color: isManager ? "#fff" : "#64748b", textTransform: "capitalize" }}>{m.role}</div>
                          <div style={{ padding: "3px 9px", borderRadius: 20, background: "#f0fdf4", fontSize: 10, fontWeight: 600, color: "#16a34a", border: "1px solid #86efac" }}>Active</div>
                          {!isManager && <button onClick={() => handleRemove(m.id, m.email)} disabled={removingId === m.id} style={{ background: "none", border: "none", color: "#cbd5e1", cursor: "pointer", fontSize: 16, padding: "0 4px" }}>×</button>}
                        </div>
                        {!isManager && (
                          <div style={{ padding: "8px 16px 12px", borderTop: "1px solid #f1f5f9" }}>
                            {editingNoteFor === m.id ? (
                              <div style={{ display: "flex", gap: 6 }}>
                                <input value={noteInput} onChange={e => setNoteInput(e.target.value)} onKeyDown={e => { if (e.key === "Enter") handleSaveNote(m.id); if (e.key === "Escape") setEditingNoteFor(null); }} placeholder="e.g. Struggling with price objections..." autoFocus style={{ flex: 1, padding: "6px 10px", borderRadius: 6, border: "1px solid #e2e8f0", background: "#f8fafc", fontSize: 11, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none" }} />
                                <button onClick={() => handleSaveNote(m.id)} style={{ padding: "6px 12px", borderRadius: 6, background: "#1e293b", border: "none", color: "#fff", fontSize: 11, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Save</button>
                                <button onClick={() => setEditingNoteFor(null)} style={{ padding: "6px 10px", borderRadius: 6, background: "transparent", border: "1px solid #e2e8f0", color: "#64748b", fontSize: 11, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>✕</button>
                              </div>
                            ) : (
                              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                                {repNotes[m.id] ? <div style={{ fontSize: 11, color: "#64748b", flex: 1, fontStyle: "italic" }}>📝 {repNotes[m.id]}</div> : <div style={{ fontSize: 11, color: "#cbd5e1", flex: 1 }}>No notes yet</div>}
                                <button onClick={() => { setEditingNoteFor(m.id); setNoteInput(repNotes[m.id] || ""); }} style={{ background: "none", border: "none", color: "#94a3b8", cursor: "pointer", fontSize: 11, fontFamily: "'Inter', sans-serif", padding: "0 4px" }}>{repNotes[m.id] ? "Edit" : "+ Add note"}</button>
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}

          {/* OBJECTION LIBRARY */}
          {teamView === "library" && (
            <div style={{ maxWidth: 720 }}>
              <div style={{ marginBottom: 24 }}>
                <div style={{ fontSize: 20, fontWeight: 700, color: "#0f172a", marginBottom: 4 }}>Shared Objection Library</div>
                <div style={{ fontSize: 13, color: "#64748b" }}>Default responses your team trains with, plus custom ones you add.</div>
              </div>

              <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 12 }}>DEFAULT OBJECTIONS</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 28 }}>
                {mockObjections.map((obj) => (
                  <div key={obj.id} style={{ padding: "18px", borderRadius: 12, background: "#ffffff", border: "1px solid #e2e8f0" }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <div style={{ padding: "3px 9px", borderRadius: 20, background: "#f1f5f9", fontSize: 10, fontWeight: 700, color: "#4b5563" }}>{obj.category.toUpperCase()}</div>
                        <div style={{ fontSize: 13, fontWeight: 600, color: "#1e293b" }}>"{obj.objection}"</div>
                      </div>
                      <button onClick={() => setEditingObjection(editingObjection === obj.id ? null : obj.id)} style={{ padding: "5px 12px", borderRadius: 7, background: editingObjection === obj.id ? "#1e293b" : "transparent", border: "1px solid #e2e8f0", color: editingObjection === obj.id ? "#fff" : "#64748b", fontSize: 11, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>{editingObjection === obj.id ? "Save" : "Edit"}</button>
                    </div>
                    {editingObjection === obj.id ? (
                      <textarea defaultValue={obj.response} style={{ width: "100%", padding: "10px 12px", borderRadius: 8, border: "1px solid #cbd5e1", background: "#f8fafc", fontSize: 12.5, color: "#1e293b", fontFamily: "'Inter', sans-serif", lineHeight: 1.65, resize: "vertical", minHeight: 100, outline: "none", boxSizing: "border-box" }} />
                    ) : (
                      <div style={{ fontSize: 12.5, color: "#475569", lineHeight: 1.65 }}>{obj.response}</div>
                    )}
                  </div>
                ))}
              </div>

              {customObjections.length > 0 && (
                <div style={{ marginBottom: 24 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 12 }}>YOUR TEAM'S OBJECTIONS ({customObjections.length})</div>
                  {customObjections.map((obj) => (
                    <div key={obj.id} style={{ padding: "18px", borderRadius: 12, background: "#ffffff", border: "1px solid #e2e8f0", marginBottom: 10 }}>
                      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 8, flex: 1 }}>
                          <div style={{ padding: "3px 9px", borderRadius: 20, background: "#eff6ff", fontSize: 10, fontWeight: 700, color: "#2563eb", border: "1px solid #bfdbfe", flexShrink: 0 }}>{obj.category.toUpperCase()}</div>
                          <div style={{ fontSize: 13, fontWeight: 600, color: "#1e293b" }}>"{obj.objection}"</div>
                        </div>
                        <div style={{ display: "flex", gap: 6, marginLeft: 8 }}>
                          <button onClick={() => { setEditingCustomObj(editingCustomObj === obj.id ? null : obj.id); setEditedObjResponse(obj.response); }} style={{ padding: "5px 12px", borderRadius: 7, background: editingCustomObj === obj.id ? "#1e293b" : "transparent", border: "1px solid #e2e8f0", color: editingCustomObj === obj.id ? "#fff" : "#64748b", fontSize: 11, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>{editingCustomObj === obj.id ? "Cancel" : "Edit"}</button>
                          {editingCustomObj === obj.id && <button onClick={() => handleSaveEditedObjection(obj.id)} style={{ padding: "5px 12px", borderRadius: 7, background: "#16a34a", border: "none", color: "#fff", fontSize: 11, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Save</button>}
                          <button onClick={() => handleDeleteObjection(obj.id)} disabled={deletingObjId === obj.id} style={{ background: "none", border: "none", color: "#cbd5e1", cursor: "pointer", fontSize: 18, padding: "0 4px" }}>×</button>
                        </div>
                      </div>
                      {editingCustomObj === obj.id ? (
                        <textarea value={editedObjResponse} onChange={e => setEditedObjResponse(e.target.value)} style={{ width: "100%", padding: "10px 12px", borderRadius: 8, border: "1px solid #cbd5e1", background: "#f8fafc", fontSize: 12.5, color: "#1e293b", fontFamily: "'Inter', sans-serif", lineHeight: 1.65, resize: "vertical", minHeight: 100, outline: "none", boxSizing: "border-box" }} />
                      ) : (
                        <div style={{ fontSize: 12.5, color: "#475569", lineHeight: 1.65 }}>{obj.response}</div>
                      )}
                    </div>
                  ))}
                </div>
              )}

              {!showObjectionForm ? (
                <button onClick={() => setShowObjectionForm(true)} style={{ width: "100%", padding: "13px", borderRadius: 10, background: "#f8fafc", border: "2px dashed #e2e8f0", color: "#64748b", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>+ Add New Objection Response</button>
              ) : (
                <div style={{ padding: "20px", borderRadius: 12, background: "#ffffff", border: "1px solid #e2e8f0" }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: "#0f172a", marginBottom: 16 }}>New Objection Response</div>
                  <div style={{ marginBottom: 12 }}>
                    <div style={{ fontSize: 11, fontWeight: 600, color: "#64748b", marginBottom: 6 }}>CATEGORY</div>
                    <select value={newObjCategory} onChange={e => setNewObjCategory(e.target.value)} style={{ width: "100%", padding: "9px 12px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#f8fafc", fontSize: 13, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none" }}>
                      {OBJ_CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
                    </select>
                  </div>
                  <div style={{ marginBottom: 12 }}>
                    <div style={{ fontSize: 11, fontWeight: 600, color: "#64748b", marginBottom: 6 }}>THE OBJECTION</div>
                    <input value={newObjText} onChange={e => setNewObjText(e.target.value)} placeholder='e.g. "We already have something in place."' style={{ width: "100%", padding: "9px 12px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#f8fafc", fontSize: 13, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none", boxSizing: "border-box" }} />
                  </div>
                  <div style={{ marginBottom: 16 }}>
                    <div style={{ fontSize: 11, fontWeight: 600, color: "#64748b", marginBottom: 6 }}>YOUR TEAM'S RESPONSE</div>
                    <textarea value={newObjResponse} onChange={e => setNewObjResponse(e.target.value)} placeholder="Write the ideal response..." rows={5} style={{ width: "100%", padding: "9px 12px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#f8fafc", fontSize: 13, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none", resize: "vertical", lineHeight: 1.6, boxSizing: "border-box" }} />
                  </div>
                  <div style={{ display: "flex", gap: 8 }}>
                    <button onClick={handleSaveObjection} disabled={!newObjText.trim() || !newObjResponse.trim() || savingObjection} style={{ flex: 1, padding: "10px", borderRadius: 8, background: (!newObjText.trim() || !newObjResponse.trim()) ? "#e2e8f0" : "#1e293b", border: "none", color: (!newObjText.trim() || !newObjResponse.trim()) ? "#94a3b8" : "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>{savingObjection ? "Saving..." : "Save to Library"}</button>
                    <button onClick={() => { setShowObjectionForm(false); setNewObjText(""); setNewObjResponse(""); setNewObjCategory("Price"); }} style={{ padding: "10px 16px", borderRadius: 8, background: "transparent", border: "1px solid #e2e8f0", color: "#64748b", fontSize: 13, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Cancel</button>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* REP ONBOARDING */}
          {teamView === "onboarding" && (
            <div style={{ maxWidth: 720 }}>
              <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 24, gap: 16 }}>
                <div>
                  <div style={{ fontSize: 20, fontWeight: 700, color: "#0f172a", marginBottom: 4 }}>Rep Onboarding Program</div>
                  <div style={{ fontSize: 13, color: "#64748b" }}>Use the built-in program or build your own with custom sessions, videos, and resources.</div>
                </div>
                <button onClick={() => { navigator.clipboard.writeText(ONBOARDING_MESSAGE); setCopiedOnboarding(true); setTimeout(() => setCopiedOnboarding(false), 2500); }} style={{ padding: "9px 16px", borderRadius: 8, flexShrink: 0, background: copiedOnboarding ? "#f0fdf4" : "#1e293b", border: copiedOnboarding ? "1px solid #86efac" : "none", color: copiedOnboarding ? "#16a34a" : "#fff", fontSize: 12, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>{copiedOnboarding ? "✓ Copied!" : "📋 Copy all modules"}</button>
              </div>

              <div style={{ display: "flex", gap: 8, marginBottom: 24, padding: "4px", background: "#f1f5f9", borderRadius: 10, width: "fit-content" }}>
                {[{ label: "Default Program", val: false }, { label: "Custom Program", val: true }].map(opt => (
                  <button key={String(opt.val)} onClick={() => toggleCustomOnboarding(opt.val)} style={{ padding: "8px 18px", borderRadius: 8, border: "none", fontSize: 12, fontWeight: 600, cursor: "pointer", background: useCustomOnboarding === opt.val ? "#ffffff" : "transparent", color: useCustomOnboarding === opt.val ? "#0f172a" : "#94a3b8", boxShadow: useCustomOnboarding === opt.val ? "0 1px 3px rgba(0,0,0,0.1)" : "none", fontFamily: "'Inter', sans-serif" }}>{opt.label}</button>
                ))}
              </div>

              {!useCustomOnboarding && (
                <>
                  <div style={{ padding: "14px 18px", borderRadius: 10, background: "#eff6ff", border: "1px solid #bfdbfe", marginBottom: 24, fontSize: 12, color: "#2563eb", lineHeight: 1.6 }}>
                    💡 Copy individual modules or use "Copy all modules" to paste into Slack, email, or text. Each module shows which app tab the rep should use.
                  </div>
                  {ONBOARDING_MODULES.map((s, i) => {
                    const chipStyles = {
                      blue:   { background: "#E6F1FB", color: "#185FA5", border: "1px solid #B5D4F4" },
                      teal:   { background: "#E1F5EE", color: "#0F6E56", border: "1px solid #9FE1CB" },
                      purple: { background: "#EEEDFE", color: "#3C3489", border: "1px solid #CECBF6" },
                      amber:  { background: "#FAEEDA", color: "#854F0B", border: "1px solid #FAC775" },
                      coral:  { background: "#FAECE7", color: "#993C1D", border: "1px solid #F5C4B3" },
                    };
                    return (
                      <div key={i} style={{ display: "flex", gap: 16, padding: "18px", borderRadius: 12, background: "#ffffff", border: "1px solid #e2e8f0", marginBottom: 10 }}>
                        <div style={{ width: 36, height: 36, borderRadius: 9, background: "#1e293b", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, color: "#fff", flexShrink: 0 }}>{s.num}</div>
                        <div style={{ flex: 1 }}>
                          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                            <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>{s.title}</div>
                            <div style={{ fontSize: 10, color: "#94a3b8", background: "#f1f5f9", padding: "2px 8px", borderRadius: 10 }}>{s.duration}</div>
                          </div>
                          <div style={{ fontSize: 12.5, color: "#64748b", lineHeight: 1.6, marginBottom: 10 }}>{s.desc}</div>
                          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
                            <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                              {s.chips.map((chip, ci) => (
                                <span key={ci} style={{ fontSize: 11, fontWeight: 600, padding: "3px 10px", borderRadius: 20, ...chipStyles[chip.color] }}>{chip.label}</span>
                              ))}
                            </div>
                            <ModuleCopyButton text={s.copy} />
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </>
              )}

              {useCustomOnboarding && (
                <>
                  {customSessions.length === 0 && !showSessionForm && (
                    <div style={{ textAlign: "center", padding: "40px 24px", borderRadius: 12, background: "#ffffff", border: "2px dashed #e2e8f0", marginBottom: 16 }}>
                      <div style={{ fontSize: 32, marginBottom: 12 }}>📋</div>
                      <div style={{ fontSize: 14, fontWeight: 600, color: "#1e293b", marginBottom: 6 }}>No custom sessions yet</div>
                      <button onClick={() => setShowSessionForm(true)} style={{ padding: "10px 20px", borderRadius: 8, background: "#1e293b", border: "none", color: "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>+ Add First Session</button>
                    </div>
                  )}

                  {customSessions.length > 0 && (
                    <div style={{ marginBottom: 16 }}>
                      {customSessions.map((s, i) => (
                        <div key={s.id} style={{ padding: "18px", borderRadius: 12, background: "#ffffff", border: "1px solid #e2e8f0", marginBottom: 10 }}>
                          <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
                            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4, flexShrink: 0 }}>
                              <div style={{ width: 36, height: 36, borderRadius: 9, background: "#1e293b", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, color: "#fff" }}>{String(i + 1).padStart(2, "0")}</div>
                              <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                                <button onClick={() => handleMoveSession(s.id, -1)} disabled={i === 0} style={{ background: "none", border: "1px solid #e2e8f0", borderRadius: 4, padding: "1px 5px", cursor: i === 0 ? "not-allowed" : "pointer", fontSize: 10, color: i === 0 ? "#e2e8f0" : "#64748b" }}>▲</button>
                                <button onClick={() => handleMoveSession(s.id, 1)} disabled={i === customSessions.length - 1} style={{ background: "none", border: "1px solid #e2e8f0", borderRadius: 4, padding: "1px 5px", cursor: i === customSessions.length - 1 ? "not-allowed" : "pointer", fontSize: 10, color: i === customSessions.length - 1 ? "#e2e8f0" : "#64748b" }}>▼</button>
                              </div>
                            </div>
                            <div style={{ flex: 1 }}>
                              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6 }}>
                                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                                  <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>{s.title}</div>
                                  <div style={{ fontSize: 10, color: "#94a3b8", background: "#f1f5f9", padding: "2px 8px", borderRadius: 10 }}>{s.duration}</div>
                                </div>
                                <div style={{ display: "flex", gap: 6 }}>
                                  <button onClick={() => startEditSession(s)} style={{ padding: "4px 10px", borderRadius: 6, background: "transparent", border: "1px solid #e2e8f0", color: "#64748b", fontSize: 11, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Edit</button>
                                  <button onClick={() => handleDeleteSession(s.id)} disabled={deletingSessionId === s.id} style={{ background: "none", border: "none", color: "#cbd5e1", cursor: "pointer", fontSize: 18, padding: "0 4px" }}>×</button>
                                </div>
                              </div>
                              <div style={{ fontSize: 12.5, color: "#64748b", lineHeight: 1.6 }}>{s.description}</div>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}

                  {showSessionForm ? (
                    <div style={{ padding: "20px", borderRadius: 12, background: "#ffffff", border: "1px solid #e2e8f0", marginBottom: 16 }}>
                      <div style={{ fontSize: 13, fontWeight: 700, color: "#0f172a", marginBottom: 16 }}>{editingSessionId ? "Edit Session" : "New Session"}</div>
                      <div style={{ display: "flex", gap: 12, marginBottom: 12 }}>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: 11, fontWeight: 600, color: "#64748b", marginBottom: 6 }}>SESSION TITLE</div>
                          <input value={sessionForm.title} onChange={e => setSessionForm(p => ({ ...p, title: e.target.value }))} placeholder="e.g. Product Deep Dive" style={{ width: "100%", padding: "9px 12px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#f8fafc", fontSize: 13, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none", boxSizing: "border-box" }} />
                        </div>
                        <div style={{ width: 120 }}>
                          <div style={{ fontSize: 11, fontWeight: 600, color: "#64748b", marginBottom: 6 }}>DURATION</div>
                          <input value={sessionForm.duration} onChange={e => setSessionForm(p => ({ ...p, duration: e.target.value }))} placeholder="~30 min" style={{ width: "100%", padding: "9px 12px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#f8fafc", fontSize: 13, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none", boxSizing: "border-box" }} />
                        </div>
                      </div>
                      <div style={{ marginBottom: 12 }}>
                        <div style={{ fontSize: 11, fontWeight: 600, color: "#64748b", marginBottom: 6 }}>DESCRIPTION</div>
                        <textarea value={sessionForm.description} onChange={e => setSessionForm(p => ({ ...p, description: e.target.value }))} rows={4} style={{ width: "100%", padding: "9px 12px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#f8fafc", fontSize: 13, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none", resize: "vertical", lineHeight: 1.6, boxSizing: "border-box" }} />
                      </div>
                      <div style={{ marginBottom: 12 }}>
                        <div style={{ fontSize: 11, fontWeight: 600, color: "#64748b", marginBottom: 6 }}>VIDEO LINK <span style={{ fontWeight: 400, color: "#94a3b8" }}>(optional)</span></div>
                        <input value={sessionForm.video_url} onChange={e => setSessionForm(p => ({ ...p, video_url: e.target.value }))} placeholder="https://loom.com/share/..." style={{ width: "100%", padding: "9px 12px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#f8fafc", fontSize: 13, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none", boxSizing: "border-box" }} />
                      </div>
                      <div style={{ display: "flex", gap: 8 }}>
                        <button onClick={handleSaveSession} disabled={!sessionForm.title.trim() || !sessionForm.description.trim() || savingSession} style={{ flex: 1, padding: "10px", borderRadius: 8, background: (!sessionForm.title.trim() || !sessionForm.description.trim()) ? "#e2e8f0" : "#1e293b", border: "none", color: (!sessionForm.title.trim() || !sessionForm.description.trim()) ? "#94a3b8" : "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>{savingSession ? "Saving..." : editingSessionId ? "Save Changes" : "Add Session"}</button>
                        <button onClick={() => { setShowSessionForm(false); setEditingSessionId(null); setSessionForm({ title: "", description: "", duration: "~30 min", video_url: "", resource_links: [] }); }} style={{ padding: "10px 16px", borderRadius: 8, background: "transparent", border: "1px solid #e2e8f0", color: "#64748b", fontSize: 13, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Cancel</button>
                      </div>
                    </div>
                  ) : customSessions.length > 0 && (
                    <button onClick={() => setShowSessionForm(true)} style={{ width: "100%", padding: "13px", borderRadius: 10, background: "#f8fafc", border: "2px dashed #e2e8f0", color: "#64748b", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>+ Add Another Session</button>
                  )}
                </>
              )}
            </div>
          )}

          {/* BUYER PERSONAS */}
          {teamView === "personas" && (
            <div style={{ maxWidth: 680 }}>
              <div style={{ marginBottom: 24 }}>
                <div style={{ fontSize: 20, fontWeight: 700, color: "#0f172a", marginBottom: 4 }}>Buyer Personas Library</div>
                <div style={{ fontSize: 13, color: "#64748b" }}>Shared buyer personas your whole team practices against.</div>
              </div>

              <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 12 }}>DEFAULT PERSONAS</div>
              {[
                { name: "The Skeptical Homeowner", tags: ["Price", "Timing"], desc: "Mid-50s, already has two quotes, very price-sensitive. Main objections: timing and needing to think about it." },
                { name: "The Busy Executive", tags: ["Authority", "Timing"], desc: "C-suite or VP level. Needs ROI framed in minutes. Main objection: too busy to evaluate right now." },
                { name: "The Committee Buyer", tags: ["Competition", "Trust"], desc: "Procurement-driven. Multiple stakeholders. Main objection: we need to evaluate other options." },
              ].map((p, i) => (
                <div key={i} style={{ padding: "18px", borderRadius: 12, background: "#ffffff", border: "1px solid #e2e8f0", marginBottom: 10 }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>{p.name}</div>
                    <div style={{ display: "flex", gap: 6 }}>
                      {p.tags.map((t, j) => <div key={j} style={{ padding: "2px 9px", borderRadius: 20, background: "#f1f5f9", fontSize: 10, fontWeight: 600, color: "#4b5563" }}>{t}</div>)}
                    </div>
                  </div>
                  <div style={{ fontSize: 12.5, color: "#64748b", lineHeight: 1.6 }}>{p.desc}</div>
                </div>
              ))}

              {customPersonas.length > 0 && (
                <div style={{ marginTop: 24 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 12 }}>YOUR TEAM'S PERSONAS ({customPersonas.length})</div>
                  {customPersonas.map((p) => (
                    <div key={p.id} style={{ padding: "18px", borderRadius: 12, background: "#ffffff", border: "1px solid #e2e8f0", marginBottom: 10 }}>
                      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
                        <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>{p.name}</div>
                        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                          {(p.tags || []).map((t, j) => <div key={j} style={{ padding: "2px 9px", borderRadius: 20, background: "#eff6ff", fontSize: 10, fontWeight: 600, color: "#2563eb", border: "1px solid #bfdbfe" }}>{t}</div>)}
                          <button onClick={() => handleDeletePersona(p.id)} disabled={deletingPersonaId === p.id} style={{ background: "none", border: "none", color: "#cbd5e1", cursor: "pointer", fontSize: 18, padding: "0 4px" }}>×</button>
                        </div>
                      </div>
                      <div style={{ fontSize: 12.5, color: "#64748b", lineHeight: 1.6 }}>{p.description}</div>
                    </div>
                  ))}
                </div>
              )}

              <div style={{ marginTop: 24 }}>
                {!showPersonaForm ? (
                  <button onClick={() => setShowPersonaForm(true)} style={{ width: "100%", padding: "13px", borderRadius: 10, background: "#f8fafc", border: "2px dashed #e2e8f0", color: "#64748b", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>+ Build New Persona</button>
                ) : (
                  <div style={{ padding: "20px", borderRadius: 12, background: "#ffffff", border: "1px solid #e2e8f0" }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: "#0f172a", marginBottom: 16 }}>New Buyer Persona</div>
                    <div style={{ marginBottom: 12 }}>
                      <div style={{ fontSize: 11, fontWeight: 600, color: "#64748b", marginBottom: 6 }}>PERSONA NAME</div>
                      <input value={newPersonaName} onChange={e => setNewPersonaName(e.target.value)} placeholder="e.g. The Reluctant Decision Maker" style={{ width: "100%", padding: "9px 12px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#f8fafc", fontSize: 13, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none", boxSizing: "border-box" }} />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                      <div style={{ fontSize: 11, fontWeight: 600, color: "#64748b", marginBottom: 6 }}>OBJECTION TAGS</div>
                      <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                        {AVAILABLE_TAGS.map(tag => (
                          <button key={tag} onClick={() => setNewPersonaTags(prev => prev.includes(tag) ? prev.filter(t => t !== tag) : [...prev, tag])} style={{ padding: "4px 12px", borderRadius: 20, fontSize: 11, fontWeight: 600, cursor: "pointer", border: newPersonaTags.includes(tag) ? "1px solid #3b82f6" : "1px solid #e2e8f0", background: newPersonaTags.includes(tag) ? "#eff6ff" : "#f8fafc", color: newPersonaTags.includes(tag) ? "#2563eb" : "#64748b", fontFamily: "'Inter', sans-serif" }}>{tag}</button>
                        ))}
                      </div>
                    </div>
                    <div style={{ marginBottom: 16 }}>
                      <div style={{ fontSize: 11, fontWeight: 600, color: "#64748b", marginBottom: 6 }}>DESCRIPTION</div>
                      <textarea value={newPersonaDesc} onChange={e => setNewPersonaDesc(e.target.value)} placeholder="Describe this buyer..." rows={4} style={{ width: "100%", padding: "9px 12px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#f8fafc", fontSize: 13, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none", resize: "vertical", lineHeight: 1.6, boxSizing: "border-box" }} />
                    </div>
                    <div style={{ display: "flex", gap: 8 }}>
                      <button onClick={handleSavePersona} disabled={!newPersonaName.trim() || !newPersonaDesc.trim() || savingPersona} style={{ flex: 1, padding: "10px", borderRadius: 8, background: (!newPersonaName.trim() || !newPersonaDesc.trim()) ? "#e2e8f0" : "#1e293b", border: "none", color: (!newPersonaName.trim() || !newPersonaDesc.trim()) ? "#94a3b8" : "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>{savingPersona ? "Saving..." : "Save Persona"}</button>
                      <button onClick={() => { setShowPersonaForm(false); setNewPersonaName(""); setNewPersonaDesc(""); setNewPersonaTags([]); }} style={{ padding: "10px 16px", borderRadius: 8, background: "transparent", border: "1px solid #e2e8f0", color: "#64748b", fontSize: 13, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Cancel</button>
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* TEAM NOTES */}
          {teamView === "report" && (
            <div style={{ maxWidth: 640 }}>
              <div style={{ marginBottom: 24 }}>
                <div style={{ fontSize: 20, fontWeight: 700, color: "#0f172a", marginBottom: 4 }}>Team Notes</div>
                <div style={{ fontSize: 13, color: "#64748b" }}>A private scratch pad for you as manager. Only you can see this.</div>
              </div>
              <textarea value={teamNotes} onChange={e => setTeamNotes(e.target.value)} rows={18} style={{ width: "100%", padding: "16px", borderRadius: 12, border: "1px solid #e2e8f0", background: "#ffffff", fontSize: 13, color: "#1e293b", fontFamily: "'Inter', sans-serif", outline: "none", resize: "vertical", lineHeight: 1.7, boxSizing: "border-box" }} />
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 12 }}>
                <div style={{ fontSize: 11, color: "#94a3b8" }}>Only visible to you.</div>
                <button onClick={handleSaveTeamNotes} disabled={savingTeamNotes} style={{ padding: "9px 20px", borderRadius: 8, background: teamNotesSaved ? "#f0fdf4" : "#1e293b", border: teamNotesSaved ? "1px solid #86efac" : "none", color: teamNotesSaved ? "#16a34a" : "#fff", fontSize: 12, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>{savingTeamNotes ? "Saving..." : teamNotesSaved ? "✓ Saved!" : "Save Notes"}</button>
              </div>
            </div>
          )}

        </div>
      </div>

      {/* ── Manager Guide Modal ── */}
      {showHelp && (
        <div onClick={() => setShowHelp(false)} style={{
          position: "fixed", inset: 0, background: "rgba(0,0,0,0.5)",
          zIndex: 9999, display: "flex", alignItems: "center", justifyContent: "center",
          padding: 24, fontFamily: "'Inter', sans-serif",
        }}>
          <div onClick={e => e.stopPropagation()} style={{
            background: "#fff", borderRadius: 12, width: "100%", maxWidth: 680,
            maxHeight: "90vh", overflow: "hidden", display: "flex", flexDirection: "column",
            boxShadow: "0 20px 60px rgba(0,0,0,0.25)",
          }}>
            <div style={{ padding: "20px 24px 16px", borderBottom: "1px solid #e2e8f0", display: "flex", justifyContent: "space-between", alignItems: "center", flexShrink: 0 }}>
              <div>
                <div style={{ fontSize: 16, fontWeight: 700, color: "#0f172a" }}>📖 Manager Guide</div>
                <div style={{ fontSize: 12, color: "#64748b", marginTop: 2 }}>Everything you need to run your team dashboard</div>
              </div>
              <button onClick={() => setShowHelp(false)} style={{ background: "none", border: "none", fontSize: 20, cursor: "pointer", color: "#94a3b8", lineHeight: 1 }}>✕</button>
            </div>
            <div style={{ overflowY: "auto", padding: "24px", flex: 1 }}>
              {[
                { icon: "🏷️", title: "Rename Your Team", body: "Click the team name at the top of the dashboard (or the ✏️ icon) to edit it. Type your new name and click Save." },
                { icon: "👥", title: "Inviting Reps", body: "Go to the Members tab. Enter a rep's email and click Send Invite. They'll get a magic link to join. You have 10 seats included. Pending invites show a badge on the Members tab — you can resend anytime." },
                { icon: "🗑️", title: "Removing a Member", body: "In the Members tab, click Remove next to any member to free up their seat." },
                { icon: "🏆", title: "Leaderboard", body: "The Leaderboard tab ranks your reps by their CIS (Confidence & Impact Score) from AI sessions. Use it in team meetings to motivate practice." },
                { icon: "📝", title: "Rep Notes", body: "In the Members tab, click the notepad icon next to any rep to add private coaching notes only you can see." },
                { icon: "📚", title: "Objection Library", body: "Build a shared bank of objections and approved responses your reps can study. Click New Objection, choose a category, enter the objection and your ideal response. Edit responses anytime." },
                { icon: "🧑‍💼", title: "Rep Onboarding", body: "Build a custom training track for new reps. Toggle Use Custom Onboarding ON, then click Add Session to create modules with titles, descriptions, videos, and resource links. Drag sessions to reorder them." },
                { icon: "🎯", title: "Buyer Personas", body: "Create customer profiles your reps practice against. Click New Persona, give it a name, description, and tags. Reps can select your personas when starting AI roleplay sessions." },
                { icon: "🗒️", title: "Team Notes", body: "A private notepad only you can see. Use it for team goals, meeting recaps, or anything you want to track. Saves automatically." },
              ].map((item, i, arr) => (
                <div key={i} style={{ marginBottom: 20, paddingBottom: 20, borderBottom: i < arr.length - 1 ? "1px solid #f1f5f9" : "none" }}>
                  <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                    <div style={{ fontSize: 20, lineHeight: 1.4, flexShrink: 0 }}>{item.icon}</div>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: "#0f172a", marginBottom: 4 }}>{item.title}</div>
                      <div style={{ fontSize: 13, color: "#475569", lineHeight: 1.6 }}>{item.body}</div>
                    </div>
                  </div>
                </div>
              ))}
              <div style={{ background: "#f8fafc", borderRadius: 8, padding: "14px 16px", marginTop: 8 }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: "#0369a1", marginBottom: 6 }}>💡 Quick Tips</div>
                <div style={{ fontSize: 12, color: "#475569", lineHeight: 1.8 }}>
                  • Check the Leaderboard weekly and celebrate top performers<br/>
                  • Set a team standard of 2+ sessions per week<br/>
                  • Build your Objection Library before inviting reps<br/>
                  • Use rep notes after every 1:1 to track coaching progress
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

    </div>
  );
}

// ─── Changelog type styles ─────────────────────────────────────────────────────
const typeStyle = {
  new: { label: "NEW", bg: "#f0fdf4", border: "#86efac", color: "#16a34a" },
  fix: { label: "FIX", bg: "#eff6ff", border: "#93c5fd", color: "#2563eb" },
  update: { label: "UPD", bg: "#fefce8", border: "#fde68a", color: "#ca8a04" },
};

function ChangelogModal({ isLoggedIn, onClose }) {
  const CHANGELOG = [
    {
      version: "v1.7", tag: "LATEST", tagColor: "#3b82f6", date: "March 2026",
      changes: [
        { type: "new", text: "Usage restrictions: Free users limited to 3 objection practices/session and 5 sessions/week" },
        { type: "new", text: "Free session limit popup with reset time and Pro upgrade CTA" },
        { type: "new", text: "Pro/Team 300k token/month cap tracked per user in Supabase" },
        { type: "new", text: "Token warning popup when within 10k tokens of monthly limit" },
        { type: "new", text: "Token top-up offer: $19 one-time for +300k tokens (30 days) when limit is hit" },
      ]
    },
    {
      version: "v1.6", tag: "PREV", tagColor: "#64748b", date: "March 2026",
      changes: [
        { type: "fix", text: "Fixed duplicate useState declarations causing SyntaxError in TeamDashboard" },
        { type: "fix", text: "Fixed duplicate function declarations (handleSaveTeamName, handleSaveNote, handleResendInvite, handleSaveTeamNotes)" },
        { type: "fix", text: "Fixed duplicate editingTeamName block in Team header" },
      ]
    },
    {
      version: "v1.5", tag: "PREV", tagColor: "#64748b", date: "March 2026",
      changes: [
        { type: "new", text: "Team invite system — managers can invite reps via email with real Supabase backend" },
        { type: "new", text: "Custom onboarding program builder — sessions, video links, resource links, drag-to-reorder" },
        { type: "new", text: "Objection Library — managers can add, edit, and delete custom objections saved per team" },
        { type: "new", text: "Buyer Personas — managers can build and save custom personas per team" },
      ]
    },
  ];

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "rgba(15,23,42,0.55)", backdropFilter: "blur(4px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
    }}>
      <div style={{
        background: "#fff", borderRadius: 16, padding: "28px 26px",
        maxWidth: 480, width: "100%",
        boxShadow: "0 24px 64px rgba(0,0,0,0.16)", border: "1px solid #e2e8f0",
        maxHeight: "82vh", display: "flex", flexDirection: "column",
      }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20, flexShrink: 0 }}>
          <div>
            <div style={{ fontSize: 16, fontWeight: 800, color: "#0f172a", fontFamily: "'Inter', sans-serif" }}>What's New</div>
            <div style={{ fontSize: 12, color: "#94a3b8", fontFamily: "'Inter', sans-serif", marginTop: 2 }}>{BRAND_CONFIG.appName} release history</div>
          </div>
          <button onClick={onClose} style={{ background: "none", border: "none", cursor: "pointer", color: "#94a3b8", fontSize: 20, lineHeight: 1, padding: "2px 6px" }}>×</button>
        </div>

        <div style={{ display: "inline-flex", alignItems: "center", gap: 8, background: "#f8fafc", border: "1px solid #e2e8f0", borderRadius: 8, padding: "8px 14px", marginBottom: 20, flexShrink: 0 }}>
          <div style={{ width: 7, height: 7, borderRadius: "50%", background: "#22c55e" }} />
          <span style={{ fontSize: 12, fontWeight: 700, color: "#0f172a", fontFamily: "'Inter', sans-serif" }}>Current version: v1.7</span>
          <span style={{ fontSize: 11, color: "#94a3b8", fontFamily: "'Inter', sans-serif" }}>· 2026-03-11</span>
        </div>

        <div style={{ overflowY: "auto", flex: 1 }}>
          {CHANGELOG.map((release, ri) => (
            <div key={ri} style={{ marginBottom: ri < CHANGELOG.length - 1 ? 28 : 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
                <div style={{ fontSize: 14, fontWeight: 800, color: "#0f172a", fontFamily: "'Inter', sans-serif" }}>{release.version}</div>
                <div style={{ padding: "2px 8px", borderRadius: 100, background: release.tagColor + "20", border: `1px solid ${release.tagColor}50`, fontSize: 9, fontWeight: 700, color: release.tagColor, letterSpacing: "0.08em", fontFamily: "'Inter', sans-serif" }}>{release.tag}</div>
                <div style={{ fontSize: 11, color: "#94a3b8", fontFamily: "'Inter', sans-serif", marginLeft: "auto" }}>{release.date}</div>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
                {release.changes.map((c, ci) => {
                  const s = typeStyle[c.type] || typeStyle.new;
                  return (
                    <div key={ci} style={{ display: "flex", alignItems: "flex-start", gap: 9 }}>
                      <div style={{ flexShrink: 0, marginTop: 1, padding: "1px 6px", borderRadius: 4, background: s.bg, border: `1px solid ${s.border}`, fontSize: 8, fontWeight: 700, color: s.color, letterSpacing: "0.06em", fontFamily: "'Inter', sans-serif" }}>{s.label}</div>
                      <div style={{ fontSize: 12.5, color: "#374151", fontFamily: "'Inter', sans-serif", lineHeight: 1.5 }}>{c.text}</div>
                    </div>
                  );
                })}
              </div>
              {ri < CHANGELOG.length - 1 && <div style={{ height: 1, background: "#f1f5f9", marginTop: 24 }} />}
            </div>
          ))}
        </div>

        <button onClick={onClose} style={{ marginTop: 18, width: "100%", padding: "10px", borderRadius: 10, flexShrink: 0, background: "transparent", border: "1px solid #e2e8f0", color: "#94a3b8", fontSize: 13, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Close</button>
      </div>
    </div>
  );
}

// ─── Login Screen ──────────────────────────────────────────────────────────────

// ─── About Us Page ────────────────────────────────────────────────────────────
function AboutPage({ onNav }) {
  return (
    <div style={{ maxWidth: 720, margin: "0 auto", padding: "60px 24px 80px" }}>
      <div style={{ textAlign: "center", marginBottom: 48 }}>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "#fff", border: "1px solid #e2e8f0", borderRadius: 100, padding: "5px 14px 5px 10px", fontSize: 12, fontWeight: 600, color: "#64748b", marginBottom: 20 }}>
          <span style={{ width: 7, height: 7, borderRadius: "50%", background: "#3b82f6", display: "inline-block" }} /> Our story
        </div>
        <h1 style={{ fontSize: "clamp(28px, 5vw, 44px)", fontWeight: 900, letterSpacing: "-0.03em", color: "#0f172a", lineHeight: 1.15, marginBottom: 16 }}>Built by closers,<br/>for closers.</h1>
        <p style={{ fontSize: 16, color: "#64748b", lineHeight: 1.75, maxWidth: 540, margin: "0 auto" }}>
          {BRAND_CONFIG.appName} was created out of frustration with sales training that doesn't work — generic scripts, outdated playbooks, and coaches who've never sat across from a real objection.
        </p>
      </div>

      <div style={{ background: "#0f172a", borderRadius: 16, padding: "32px 36px", marginBottom: 32, color: "#f1f5f9" }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.1em", marginBottom: 12 }}>THE MISSION</div>
        <p style={{ fontSize: 17, lineHeight: 1.75, fontWeight: 500 }}>
          Give every sales rep — whether they're selling kitchen remodels in living rooms or SaaS deals over Zoom — the same elite coaching that was previously only available to reps at the largest companies in the world.
        </p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 16, marginBottom: 40 }}>
        {[
          { icon: "🎯", title: "Real-world focused", body: "Every prompt, drill, and simulation is built around the conversations reps actually have — not textbook theory." },
          { icon: "⚡", title: "Always available", body: "24/7 coaching that adapts to your industry, your role, and your weakest skill — whenever you need it." },
          { icon: "📈", title: "Measurable results", body: "Close Intelligence Scores track your improvement across 7 metrics so you can see exactly where you're getting better." },
          { icon: "🤝", title: "Built for teams", body: "From solo reps to full sales orgs — the platform scales from individual practice to team-wide performance management." },
        ].map((c, i) => (
          <div key={i} style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 14, padding: "22px 20px" }}>
            <div style={{ fontSize: 24, marginBottom: 10 }}>{c.icon}</div>
            <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a", marginBottom: 6 }}>{c.title}</div>
            <div style={{ fontSize: 13, color: "#64748b", lineHeight: 1.6 }}>{c.body}</div>
          </div>
        ))}
      </div>

      <div style={{ background: "#eff6ff", border: "1px solid #bfdbfe", borderRadius: 14, padding: "28px 32px", textAlign: "center" }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: "#1d4ed8", marginBottom: 8 }}>Ready to train smarter?</div>
        <p style={{ fontSize: 13.5, color: "#3b82f6", marginBottom: 18, lineHeight: 1.6 }}>Join 2,400+ reps already using {BRAND_CONFIG.appName} to close more deals.</p>
        <button onClick={() => onNav("home")} style={{ padding: "11px 28px", borderRadius: 10, border: "none", background: "#1e293b", color: "#fff", fontSize: 14, fontWeight: 700, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Start training free →</button>
      </div>
    </div>
  );
}

// ─── FAQ Page ─────────────────────────────────────────────────────────────────
function FAQPage({ onNav }) {
  const [open, setOpen] = React.useState(null);
  const faqs = [
    { q: "What is " + BRAND_CONFIG.appName + "?", a: BRAND_CONFIG.appName + " is an AI-powered sales training and coaching platform. It helps sales reps practice objection handling, sharpen discovery skills, run full deal simulations, and track their performance — all through a conversational AI coach available 24/7." },
    { q: "Who is it for?", a: BRAND_CONFIG.appName + " is built for two types of sellers: in-home and showroom reps (kitchen remodeling, flooring, roofing, HVAC, solar, windows) and SaaS/AE/remote closers (Account Executives, SDRs, BDRs, remote closers). If you sell anything, you'll find value here." },
    { q: "Is it really free to start?", a: "Yes. The free plan gives you 5 AI-coached sessions per day with access to objection handling, script rewrites, and discovery question generation. No credit card required." },
    { q: "What's included in Pro?", a: "Pro ($29/mo) unlocks unlimited sessions, roleplay simulations, deal coaching, transcript analysis, Close Intelligence Scores, the Close or Lose game, the Profit Engine calculator, custom persona builder, and more." },
    { q: "What is the Team plan?", a: "The Team plan ($199/mo) gives up to 10 users full Pro access plus a manager dashboard with leaderboards, rep onboarding programs, shared objection libraries, buyer personas, and team performance tracking. It's flat-rate — no per-seat fees." },
    { q: "What is Enterprise?", a: "Enterprise is for larger sales organizations that need white-label options, a Team Performance Command Center, 2× token usage, Private Sales Arena, AI Coaching Insights, and a dedicated onboarding experience. Pricing is custom — fill out the form and we'll reach out." },
    { q: "What is a Close Intelligence Score (CIS)?", a: "The CIS is a 0–100 score across 7 metrics: Confidence, Clarity, Objection Handling, Discovery Depth, Reframe Strength, Closing Strength, and Natural Delivery. It's calculated after roleplay sessions and gives you a concrete benchmark to improve against." },
    { q: "Can I use this on mobile?", a: "Yes. " + BRAND_CONFIG.appName + " is a progressive web app (PWA). You can add it to your home screen on iOS and Android for a native app experience — no app store required." },
    { q: "How does the affiliate program work?", a: "We're building an affiliate program and it's coming soon. Get on the early access list and we'll notify you when it launches with full details on commissions and tools." },
    { q: "How do I cancel my subscription?", a: "You can cancel anytime. There are no contracts or cancellation fees. If you have a question about your billing, reach out via our contact page and we'll sort it out immediately." },
    { q: "Is my data private?", a: "Yes. Your conversations with the AI coach are used only to generate your responses and are not shared with third parties. See our Privacy Policy for full details." },
  ];
  return (
    <div style={{ maxWidth: 680, margin: "0 auto", padding: "60px 24px 80px" }}>
      <div style={{ textAlign: "center", marginBottom: 48 }}>
        <h1 style={{ fontSize: "clamp(28px, 5vw, 42px)", fontWeight: 900, letterSpacing: "-0.03em", color: "#0f172a", marginBottom: 12 }}>Frequently asked questions</h1>
        <p style={{ fontSize: 15, color: "#64748b" }}>Everything you need to know about {BRAND_CONFIG.appName}.</p>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {faqs.map((faq, i) => (
          <div key={i} onClick={() => setOpen(open === i ? null : i)} style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 12, padding: "18px 20px", cursor: "pointer", transition: "border-color 0.15s", borderColor: open === i ? "#94a3b8" : "#e2e8f0" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: "#0f172a" }}>{faq.q}</div>
              <div style={{ fontSize: 18, color: "#94a3b8", flexShrink: 0, transform: open === i ? "rotate(45deg)" : "none", transition: "transform 0.2s" }}>+</div>
            </div>
            {open === i && <div style={{ marginTop: 12, fontSize: 13.5, color: "#64748b", lineHeight: 1.7 }}>{faq.a}</div>}
          </div>
        ))}
      </div>
      <div style={{ textAlign: "center", marginTop: 48, padding: "28px", background: "#f8fafc", borderRadius: 14, border: "1px solid #e2e8f0" }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a", marginBottom: 6 }}>Still have questions?</div>
        <p style={{ fontSize: 13, color: "#64748b", marginBottom: 16 }}>We're happy to help. Reach out and we'll get back to you fast.</p>
        <a href="/contact.html" style={{ display: "inline-block", padding: "10px 24px", borderRadius: 9, background: "#1e293b", color: "#fff", fontSize: 13, fontWeight: 600, textDecoration: "none", fontFamily: "'Inter', sans-serif" }}>Contact us →</a>
      </div>
    </div>
  );
}

function LegalPageShell({ badge = "Legal", title, updated, notice, children }) {
  return (
    <div style={{ maxWidth: 860, margin: "0 auto", padding: "60px 24px 80px" }}>
      <div style={{ textAlign: "center", marginBottom: 36 }}>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "6px 14px", border: "1px solid #e2e8f0", borderRadius: 999, fontSize: 12, color: "#64748b", background: "#fff", boxShadow: "0 2px 16px rgba(15,23,42,0.07)", marginBottom: 24, fontFamily: "'JetBrains Mono', monospace" }}>
          {badge}
        </div>
        <h1 style={{ fontFamily: "'Inter', sans-serif", fontSize: "clamp(32px, 5vw, 58px)", fontWeight: 900, lineHeight: 1.05, color: "#0f172a", letterSpacing: "-0.03em", marginBottom: 12 }}>{title}</h1>
        <p style={{ fontSize: 17, color: "#64748b", lineHeight: 1.7 }}>Last updated: {updated}</p>
      </div>

      <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 16, padding: 40, boxShadow: "0 8px 40px rgba(15,23,42,0.10)" }}>
        {notice && (
          <div style={{ background: "rgba(59,130,246,0.07)", border: "1px solid rgba(59,130,246,0.18)", borderRadius: 10, padding: "12px 18px", marginBottom: 32, fontSize: 13, color: "#2563eb", lineHeight: 1.7 }}>
            {notice}
          </div>
        )}
        <div style={{ fontSize: 15, color: "#64748b", lineHeight: 1.75 }}>
          {children}
        </div>
      </div>
    </div>
  );
}

function LegalSection({ title, children }) {
  return (
    <section style={{ marginTop: 32 }}>
      <h2 style={{ fontSize: 20, fontWeight: 800, color: "#0f172a", marginBottom: 10, paddingBottom: 10, borderBottom: "1px solid #e2e8f0", letterSpacing: "-0.02em" }}>{title}</h2>
      <div>{children}</div>
    </section>
  );
}

function LegalList({ items }) {
  return (
    <ul style={{ paddingLeft: 20, margin: "0 0 14px", color: "#64748b" }}>
      {items.map((item, index) => (
        <li key={index} style={{ marginBottom: 6 }}>{item}</li>
      ))}
    </ul>
  );
}

function PrivacyPolicyPage() {
  return (
    <LegalPageShell
      title="Privacy Policy"
      updated="March 13, 2025"
      notice="Effective date: March 13, 2025. Applies to all users of thesaleslabai.com and related services."
    >
      <LegalSection title="1. Introduction">
        <p>SalesLab AI ("we," "our," or "us") is committed to protecting your privacy. This Privacy Policy explains how we collect, use, disclose, and safeguard your information when you visit <a href="https://thesaleslabai.com" style={{ color: "#2563eb" }}>thesaleslabai.com</a> and use our AI-powered sales training platform.</p>
      </LegalSection>
      <LegalSection title="2. Information We Collect">
        <LegalList items={[
          <><strong style={{ color: "#1e293b" }}>Account Information:</strong> Name, email address, and password when you register.</>,
          <><strong style={{ color: "#1e293b" }}>Payment Information:</strong> Billing details processed securely through Stripe. We do not store full card numbers.</>,
          <><strong style={{ color: "#1e293b" }}>Usage Data:</strong> Roleplay sessions, objection drill results, scores, and platform interactions.</>,
          <><strong style={{ color: "#1e293b" }}>Device and Log Data:</strong> IP address, browser type, operating system, and pages visited.</>,
          <><strong style={{ color: "#1e293b" }}>Communications:</strong> Emails or messages you send us.</>,
        ]} />
      </LegalSection>
      <LegalSection title="3. How We Use Your Information">
        <LegalList items={[
          "Provide, operate, and improve SalesLab AI services.",
          "Process payments and manage subscriptions.",
          "Personalize your training experience and track progress.",
          "Send transactional emails and, with consent, marketing communications.",
          "Monitor platform security and prevent fraud.",
          "Comply with legal obligations.",
        ]} />
      </LegalSection>
      <LegalSection title="4. Sharing of Information">
        <p>We do not sell your personal information. We may share data with trusted third parties solely to operate our service, including:</p>
        <LegalList items={[
          <><strong style={{ color: "#1e293b" }}>Stripe:</strong> payment processing</>,
          <><strong style={{ color: "#1e293b" }}>Anthropic / OpenAI:</strong> AI model infrastructure</>,
          <><strong style={{ color: "#1e293b" }}>Analytics providers:</strong> aggregated, anonymized usage data</>,
          <><strong style={{ color: "#1e293b" }}>Legal authorities:</strong> when required by law</>,
        ]} />
      </LegalSection>
      <LegalSection title="5. Cookies">
        <p>We use cookies and similar tracking technologies to enhance your experience, analyze usage, and support authentication. You can control cookies through your browser settings, though disabling them may affect functionality.</p>
      </LegalSection>
      <LegalSection title="6. Data Retention">
        <p>We retain your personal information for as long as your account is active or as needed to provide services. You may request deletion of your data at any time by contacting <a href="mailto:support@thesaleslabai.com" style={{ color: "#2563eb" }}>support@thesaleslabai.com</a>.</p>
      </LegalSection>
      <LegalSection title="7. Security">
        <p>We implement industry-standard security measures including SSL encryption, secure data storage, and access controls. However, no method of transmission over the internet is 100% secure.</p>
      </LegalSection>
      <LegalSection title="8. Children's Privacy">
        <p>SalesLab AI is not directed to individuals under the age of 16. We do not knowingly collect personal information from children.</p>
      </LegalSection>
      <LegalSection title="9. Your Rights">
        <p>Depending on your location, you may have rights including access, correction, deletion, and data portability. Contact us at <a href="mailto:support@thesaleslabai.com" style={{ color: "#2563eb" }}>support@thesaleslabai.com</a> to exercise these rights.</p>
      </LegalSection>
      <LegalSection title="10. Changes to This Policy">
        <p>We may update this Privacy Policy from time to time. Continued use of the platform after changes constitutes acceptance of the revised policy.</p>
      </LegalSection>
      <LegalSection title="11. Contact Us">
        <LegalList items={[
          <>Email: <a href="mailto:support@thesaleslabai.com" style={{ color: "#2563eb" }}>support@thesaleslabai.com</a></>,
          <>Website: <a href="https://thesaleslabai.com/contact" style={{ color: "#2563eb" }}>thesaleslabai.com/contact</a></>,
        ]} />
      </LegalSection>
    </LegalPageShell>
  );
}

function TermsOfServicePage() {
  return (
    <LegalPageShell
      title="Terms of Service"
      updated="March 13, 2025"
      notice="Effective date: March 13, 2025. Please read these terms carefully before using SalesLab AI."
    >
      <LegalSection title="1. Acceptance of Terms">
        <p>By accessing or using SalesLab AI ("Service"), you agree to be bound by these Terms of Service ("Terms"). If you do not agree, please do not use our Service. These Terms apply to all visitors, users, and others who access the Service.</p>
      </LegalSection>
      <LegalSection title="2. Description of Service">
        <p>SalesLab AI provides an AI-powered sales training platform including roleplay simulations, objection drills, close intelligence scoring, voice input training, and team dashboards. Features may change over time at our discretion.</p>
      </LegalSection>
      <LegalSection title="3. Eligibility">
        <p>You must be at least 16 years old to use this Service. By agreeing to these Terms, you represent that you are of legal age to form a binding contract.</p>
      </LegalSection>
      <LegalSection title="4. Account Registration">
        <p>To access certain features, you must create an account. You agree to:</p>
        <LegalList items={[
          "Provide accurate, current, and complete information.",
          "Maintain the security of your password and account.",
          "Promptly notify us of any unauthorized account use.",
          "Take responsibility for all activity that occurs under your account.",
        ]} />
      </LegalSection>
      <LegalSection title="5. Subscriptions and Billing">
        <p>Some features require a paid subscription. By subscribing, you agree to pay all applicable fees. Subscriptions automatically renew unless cancelled before the renewal date. All payments are processed securely through Stripe.</p>
        <p>We reserve the right to modify pricing with reasonable notice. Continued use after a price change constitutes acceptance of the new pricing.</p>
      </LegalSection>
      <LegalSection title="6. Acceptable Use">
        <p>You agree not to:</p>
        <LegalList items={[
          "Use the Service for any unlawful or fraudulent purpose.",
          "Reverse engineer, scrape, or copy any part of the platform.",
          "Share your account credentials with others.",
          "Interfere with or disrupt the integrity or performance of the Service.",
          "Upload or transmit harmful, offensive, or infringing content.",
        ]} />
      </LegalSection>
      <LegalSection title="7. Intellectual Property">
        <p>All content, features, and functionality of SalesLab AI, including AI models, training methodologies, UI design, and branding, are owned by SalesLab AI and protected by applicable intellectual property laws. You may not reproduce, distribute, or create derivative works without our express written permission.</p>
      </LegalSection>
      <LegalSection title="8. User Content">
        <p>By using the Service, you grant SalesLab AI a non-exclusive, royalty-free license to use your anonymized training data to improve our AI models and platform. We will not share personally identifiable content with third parties without your consent.</p>
      </LegalSection>
      <LegalSection title="9. Disclaimers">
        <p>The Service is provided "as is" without warranties of any kind. SalesLab AI does not guarantee specific sales results or outcomes from using the platform. AI-generated feedback is for training purposes only.</p>
      </LegalSection>
      <LegalSection title="10. Limitation of Liability">
        <p>To the maximum extent permitted by law, SalesLab AI shall not be liable for any indirect, incidental, special, or consequential damages arising from your use of the Service, even if we have been advised of the possibility of such damages.</p>
      </LegalSection>
      <LegalSection title="11. Termination">
        <p>We reserve the right to suspend or terminate your account at our discretion if you violate these Terms. Upon termination, your right to use the Service will immediately cease.</p>
      </LegalSection>
      <LegalSection title="12. Governing Law">
        <p>These Terms are governed by the laws of the United States. Any disputes shall be resolved through binding arbitration in accordance with applicable law.</p>
      </LegalSection>
      <LegalSection title="13. Changes to Terms">
        <p>We may update these Terms at any time. We will provide notice of significant changes. Continued use of the Service after changes take effect constitutes your acceptance.</p>
      </LegalSection>
      <LegalSection title="14. Contact Us">
        <LegalList items={[
          <>Email: <a href="mailto:support@thesaleslabai.com" style={{ color: "#2563eb" }}>support@thesaleslabai.com</a></>,
          <>Website: <a href="https://thesaleslabai.com/contact" style={{ color: "#2563eb" }}>thesaleslabai.com/contact</a></>,
        ]} />
      </LegalSection>
    </LegalPageShell>
  );
}

function RefundPolicyPage() {
  return (
    <LegalPageShell
      badge="Billing"
      title="Refund Policy"
      updated="March 13, 2025"
      notice="Effective date: March 13, 2025. All refund requests are handled fairly and promptly."
    >
      <div style={{ background: "rgba(22,163,74,0.08)", border: "1px solid rgba(22,163,74,0.18)", borderRadius: 12, padding: "16px 20px", marginBottom: 28, color: "#166534" }}>
        <strong style={{ color: "#166534" }}>Our commitment:</strong> We stand behind SalesLab AI. If you are not satisfied, we will do our best to make it right.
      </div>
      <LegalSection title="1. Overview">
        <p>SalesLab AI offers subscription-based access to our AI sales training platform. This policy outlines when and how refunds are issued for charges made through our platform via Stripe.</p>
      </LegalSection>
      <LegalSection title="2. Free Trial">
        <p>We offer a free tier so you can explore SalesLab AI before committing to a paid subscription. We encourage all users to try the free plan before upgrading.</p>
      </LegalSection>
      <LegalSection title="3. Subscription Refunds">
        <p><strong style={{ color: "#1e293b" }}>Monthly Subscriptions:</strong> You may request a full refund within <strong style={{ color: "#1e293b" }}>7 days</strong> of your initial purchase if you are not satisfied. After 7 days, no refunds will be issued for the current billing period, but you may cancel to prevent future charges.</p>
        <p><strong style={{ color: "#1e293b" }}>Annual Subscriptions:</strong> You may request a full refund within <strong style={{ color: "#1e293b" }}>14 days</strong> of your initial annual purchase. After 14 days, we may issue a prorated refund at our discretion based on usage.</p>
        <p><strong style={{ color: "#1e293b" }}>Renewal Charges:</strong> If you are charged for a renewal you did not intend, please contact us within <strong style={{ color: "#1e293b" }}>48 hours</strong> of the charge and we will review your request promptly.</p>
      </LegalSection>
      <LegalSection title="4. Non-Refundable Items">
        <LegalList items={[
          "Charges older than 30 days unless due to a billing error on our part.",
          "Accounts found to be in violation of our Terms of Service.",
          "Partial months or unused portions of an active subscription period for monthly plans.",
          "Add-ons or one-time purchases clearly marked as non-refundable at time of purchase.",
        ]} />
      </LegalSection>
      <LegalSection title="5. How to Request a Refund">
        <p>To request a refund, follow these steps:</p>
        <ol style={{ paddingLeft: 20, margin: "0 0 14px", color: "#64748b" }}>
          <li style={{ marginBottom: 8 }}>Email us at <a href="mailto:support@thesaleslabai.com" style={{ color: "#2563eb" }}>support@thesaleslabai.com</a> with the subject line "Refund Request."</li>
          <li style={{ marginBottom: 8 }}>Include your registered email address, the date of charge, and a brief reason for the request.</li>
          <li style={{ marginBottom: 8 }}>Our team will respond within 2 business days to confirm or request additional details.</li>
          <li style={{ marginBottom: 8 }}>Approved refunds are processed through Stripe and typically appear within 5 to 10 business days depending on your bank.</li>
        </ol>
      </LegalSection>
      <LegalSection title="6. Chargebacks">
        <p>If you initiate a chargeback through your bank without first contacting us, we reserve the right to suspend your account pending investigation. We always encourage you to reach out directly. We want to resolve issues quickly and fairly.</p>
      </LegalSection>
      <LegalSection title="7. Cancellation">
        <p>You may cancel your subscription at any time from your account settings. Cancellation stops future billing but does not automatically trigger a refund. Your access will remain active through the end of the current billing period.</p>
      </LegalSection>
      <LegalSection title="8. Contact Us">
        <LegalList items={[
          <>Email: <a href="mailto:support@thesaleslabai.com" style={{ color: "#2563eb" }}>support@thesaleslabai.com</a></>,
          <>Website: <a href="https://thesaleslabai.com/contact" style={{ color: "#2563eb" }}>thesaleslabai.com/contact</a></>,
        ]} />
      </LegalSection>
    </LegalPageShell>
  );
}

// ─── Affiliate Coming Soon Page ───────────────────────────────────────────────
function AffiliatePage() {
  const AFFILIATE_FORM = "https://docs.google.com/forms/d/e/1FAIpQLSeOLOobsAywU9nZ3j-s1BC8DdEROWTwzNgBAfkRP5OugFVSVw/viewform?usp=header";
  return (
    <div style={{ maxWidth: 600, margin: "0 auto", padding: "60px 24px 80px", textAlign: "center" }}>
      <div style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "#fef9c3", border: "1px solid #fde68a", borderRadius: 100, padding: "5px 14px 5px 10px", fontSize: 12, fontWeight: 700, color: "#92400e", marginBottom: 24, letterSpacing: "0.04em" }}>
        <span style={{ width: 7, height: 7, borderRadius: "50%", background: "#f59e0b", display: "inline-block" }} /> COMING SOON
      </div>
      <h1 style={{ fontSize: "clamp(30px, 5vw, 46px)", fontWeight: 900, letterSpacing: "-0.03em", color: "#0f172a", lineHeight: 1.15, marginBottom: 16 }}>Earn by sharing<br/>{BRAND_CONFIG.appName}.</h1>
      <p style={{ fontSize: 16, color: "#64748b", lineHeight: 1.75, marginBottom: 40, maxWidth: 480, margin: "0 auto 40px" }}>
        We're launching an affiliate program for sales professionals, coaches, and creators who want to earn recurring commissions by sharing a tool they actually believe in.
      </p>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 14, marginBottom: 40, textAlign: "left" }}>
        {[
          { icon: "💰", title: "Recurring commissions", body: "Earn on every paying customer you refer — month after month." },
          { icon: "🔗", title: "Unique affiliate link", body: "Your own trackable link with a real-time dashboard." },
          { icon: "🧰", title: "Ready-made assets", body: "Swipe copy, social graphics, and landing page templates." },
          { icon: "📈", title: "High conversion product", body: "Free to start means high click-to-signup rates for your audience." },
        ].map((c, i) => (
          <div key={i} style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 14, padding: "18px 16px" }}>
            <div style={{ fontSize: 22, marginBottom: 8 }}>{c.icon}</div>
            <div style={{ fontSize: 13, fontWeight: 700, color: "#0f172a", marginBottom: 4 }}>{c.title}</div>
            <div style={{ fontSize: 12, color: "#64748b", lineHeight: 1.55 }}>{c.body}</div>
          </div>
        ))}
      </div>

      <div style={{ background: "#0f172a", borderRadius: 16, padding: "36px 32px" }}>
        <div style={{ fontSize: 18, fontWeight: 800, color: "#f1f5f9", marginBottom: 8 }}>Get on the early access list</div>
        <p style={{ fontSize: 13.5, color: "#64748b", lineHeight: 1.65, marginBottom: 24 }}>
          Be the first to know when we launch. Early affiliates get priority onboarding and the best commission tiers.
        </p>
        <a href={AFFILIATE_FORM} target="_blank" rel="noreferrer" style={{ textDecoration: "none" }}>
          <button style={{ padding: "14px 32px", borderRadius: 11, border: "none", background: "linear-gradient(135deg, #f59e0b 0%, #f97316 100%)", color: "#fff", fontSize: 15, fontWeight: 700, cursor: "pointer", fontFamily: "'Inter', sans-serif", width: "100%", maxWidth: 340 }}>
            Join the waitlist →
          </button>
        </a>
        <div style={{ marginTop: 14, fontSize: 11, color: "#475569" }}>Takes 60 seconds. No commitment required.</div>
      </div>
    </div>
  );
}

// ─── Login / Home Screen ──────────────────────────────────────────────────────
function LoginScreen({ onLogin }) {
  const [email, setEmail] = useState("");
  const [emailSent, setEmailSent] = useState(false);
  const [authError, setAuthError] = useState("");
  const [loading, setLoading] = useState(false);
  const [activePage, setActivePage] = useState("home");
  const [menuOpen, setMenuOpen] = useState(false);

  const handleGoogle = async () => {
    setLoading(true);
    setAuthError("");
    try {
      console.log("signup clicked");
      await supabase.auth.signInWithGoogle();
    } catch {
      setAuthError("Google sign-in failed. Please try email instead.");
      setLoading(false);
    }
  };

  const handleEmail = async () => {
    if (!email.includes("@")) { setAuthError("Please enter a valid email."); return; }
    setLoading(true);
    setAuthError("");
    try {
      console.log("signup clicked");
      const ok = await supabase.auth.signInWithOtp(email);
      if (ok) { setEmailSent(true); } else { setAuthError("Couldn't send magic link. Please try again."); }
    } catch {
      setAuthError("Something went wrong. Please try again.");
    }
    setLoading(false);
  };

  const signup = () => {
    console.log("signup clicked");
  };

  const navLinks = [
    { id: "home",      label: "Home" },
    { id: "pricing",   label: "Pricing",    href: "/salespage.html" },
    { id: "about",     label: "About Us" },
    { id: "faq",       label: "FAQ" },
    { id: "contact",   label: "Contact Us", href: "/contact.html" },
  ];

  const handleNav = (id, href) => {
    setMenuOpen(false);
    if (href) { window.open(href, "_blank"); return; }
    setActivePage(id);
  };

  useEffect(() => {
    window.scrollTo({ top: 0, left: 0, behavior: "auto" });
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
  }, [activePage]);

  return (
    <div style={{ minHeight: "100svh", background: "#f8fafc", fontFamily: "'Inter', sans-serif", display: "flex", flexDirection: "column", overflowY: "auto" }}>
      <style>{`
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=DM+Serif+Display:ital@0;1&display=swap');
        @keyframes fadeUp { from { opacity:0; transform:translateY(16px); } to { opacity:1; transform:translateY(0); } }
        .fade1 { animation: fadeUp 0.5s ease both; }
        .fade2 { animation: fadeUp 0.5s 0.07s ease both; }
        .fade3 { animation: fadeUp 0.5s 0.14s ease both; }
        .fade4 { animation: fadeUp 0.5s 0.21s ease both; }
        .fade5 { animation: fadeUp 0.5s 0.28s ease both; }
        .nav-link { background: none; border: none; cursor: pointer; font-family: 'Inter', sans-serif; font-size: 13px; font-weight: 500; color: #64748b; padding: 6px 10px; border-radius: 7px; transition: color 0.15s, background 0.15s; }
        .nav-link:hover { color: #0f172a; background: #f1f5f9; }
        .nav-link.active { color: #0f172a; font-weight: 600; }
        .mobile-nav-link { display: block; width: 100%; text-align: left; background: none; border: none; cursor: pointer; font-family: 'Inter', sans-serif; font-size: 14px; font-weight: 500; color: #0f172a; padding: 12px 20px; border-bottom: 1px solid #f1f5f9; }
        .mobile-nav-link:hover { background: #f8fafc; }
        .desktop-nav { display: flex; }
        .hamburger { display: none !important; }
        @media (max-width: 640px) {
          .desktop-nav { display: none !important; }
          .hamburger { display: flex !important; }
        }
      `}</style>

      {/* Nav */}
      <div style={{ paddingTop: "env(safe-area-inset-top)", height: "calc(58px + env(safe-area-inset-top))", display: "flex", alignItems: "flex-end", justifyContent: "space-between", padding: "env(safe-area-inset-top) 24px 0", paddingBottom: 0, borderBottom: "1px solid #e2e8f0", background: "rgba(248,250,252,0.95)", backdropFilter: "blur(10px)", position: "sticky", top: 0, zIndex: 50 }}>
        <div style={{ display: "flex", alignItems: "center", height: 58 }}>
        <button onClick={() => handleNav("home")} style={{ display: "flex", alignItems: "center", gap: 9, background: "none", border: "none", cursor: "pointer", padding: 0 }}>
          <img src={BRAND_CONFIG.logoPath} alt={BRAND_CONFIG.appName} style={{ width: 30, height: 30, borderRadius: 7, objectFit: "cover" }} />
          <span style={{ fontSize: 15, fontWeight: 700, color: "#0f172a", fontFamily: "'Inter', sans-serif" }}>{BRAND_CONFIG.appName}</span>
        </button>
        </div>

        {/* Desktop nav links */}
        <div style={{ display: "flex", gap: 2, alignItems: "center", height: 58 }} className="desktop-nav">
          {navLinks.map(l => (
            <button key={l.id} onClick={() => handleNav(l.id, l.href)} className={`nav-link${activePage === l.id ? " active" : ""}`}>{l.label}</button>
          ))}
        </div>

        <div style={{ display: "flex", gap: 8, alignItems: "center", height: 58 }}>
          <button onClick={handleGoogle} style={{ padding: "7px 16px", borderRadius: 8, border: "1px solid #e2e8f0", background: "transparent", color: "#64748b", fontSize: 13, fontWeight: 500, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Sign in</button>
          <a href="/salespage.html" style={{ padding: "7px 16px", borderRadius: 8, border: "none", background: "#1e293b", color: "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif", textDecoration: "none", display: "inline-flex", alignItems: "center" }}>Book demo</a>
          {/* Hamburger for mobile */}
          <button onClick={() => setMenuOpen(!menuOpen)} style={{ display: "none", background: "none", border: "1px solid #e2e8f0", borderRadius: 7, padding: "6px 9px", cursor: "pointer", fontSize: 16, color: "#64748b" }} className="hamburger">☰</button>
        </div>
      </div>

      {/* Mobile menu dropdown */}
      {menuOpen && (
        <div style={{ position: "fixed", top: "calc(58px + env(safe-area-inset-top))", left: 0, right: 0, background: "#fff", borderBottom: "1px solid #e2e8f0", zIndex: 49, boxShadow: "0 8px 24px rgba(0,0,0,0.08)" }}>
          {navLinks.map(l => (
            <button key={l.id} onClick={() => handleNav(l.id, l.href)} className="mobile-nav-link">{l.label}</button>
          ))}
          <div style={{ padding: "12px 20px", display: "flex", gap: 10 }}>
            <button onClick={handleGoogle} style={{ flex: 1, padding: "10px", borderRadius: 8, border: "1px solid #e2e8f0", background: "transparent", color: "#64748b", fontSize: 13, fontWeight: 500, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Sign in</button>
            <a href="/salespage.html" style={{ flex: 1, padding: "10px", borderRadius: 8, border: "none", background: "#1e293b", color: "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif", textDecoration: "none", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>Book demo</a>
          </div>
        </div>
      )}

      {/* Page content */}
      <div style={{ flex: 1 }}>
        {activePage === "about" && <AboutPage onNav={handleNav} />}
        {activePage === "faq" && <FAQPage onNav={handleNav} />}
        {activePage === "privacy" && <PrivacyPolicyPage />}
        {activePage === "terms" && <TermsOfServicePage />}
        {activePage === "refund" && <RefundPolicyPage />}
        {activePage === "affiliate" && <AffiliatePage />}
        {activePage === "home" && (
          <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: "40px 24px 60px" }}>
            <div style={{ maxWidth: 680, width: "100%", textAlign: "center" }}>
              <div className="fade1" style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "#fff", border: "1px solid #e2e8f0", borderRadius: 100, padding: "5px 14px 5px 10px", fontSize: 12, fontWeight: 600, color: "#64748b", marginBottom: 24 }}>
                <span style={{ width: 7, height: 7, borderRadius: "50%", background: "#22c55e", display: "inline-block", flexShrink: 0 }} />
                Built for sales reps and the managers who coach them.
              </div>

              <h1 className="fade2" style={{ fontSize: "clamp(32px, 6vw, 52px)", fontWeight: 900, lineHeight: 1.1, letterSpacing: "-0.03em", color: "#0f172a", marginBottom: 16 }}>
                Practice real sales conversations.
                <br />
                Coach with clarity.
                <br />
                <em style={{ fontStyle: "italic", fontFamily: "'Plus Jakarta Sans', sans-serif", fontWeight: 200, color: "#1d4ed8" }}>Improve close rates.</em>
              </h1>

              <p className="fade3" style={{ fontSize: "15.5px", color: "#64748b", lineHeight: 1.7, marginBottom: 32, maxWidth: 560, margin: "0 auto 32px" }}>
                SalesLab AI helps reps practice objections, discovery, and closing in realistic AI conversations. Managers get a clear view of readiness, risk, and where coaching is needed most.
              </p>

              <div className="fade3" style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 10, margin: "0 auto 22px", maxWidth: 620 }}>
                {[
                  { title: "Rep practice", body: "Improve objections, discovery, tonality, and closing before the real call." },
                  { title: "Manager visibility", body: "See who is ready, who is slipping, and who needs coaching next." },
                  { title: "Coaching proof", body: "Coach from scored simulations and transcripts instead of guesswork." },
                ].map((item) => (
                  <div key={item.title} style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 14, padding: "14px 14px 13px", textAlign: "left", boxShadow: "0 2px 12px rgba(15,23,42,0.04)" }}>
                    <div style={{ fontSize: 12, fontWeight: 700, color: "#0f172a", marginBottom: 5 }}>{item.title}</div>
                    <div style={{ fontSize: 11.5, color: "#64748b", lineHeight: 1.55 }}>{item.body}</div>
                  </div>
                ))}
              </div>

              <div className="fade4" style={{ display: "flex", justifyContent: "center", gap: 10, flexWrap: "wrap", marginBottom: 20 }}>
                <a href="/salespage.html" style={{ padding: "11px 18px", borderRadius: 10, background: "#1e293b", color: "#fff", fontSize: 13.5, fontWeight: 700, textDecoration: "none", fontFamily: "'Inter', sans-serif" }}>
                  Book enterprise demo ->
                </a>
                <button onClick={handleGoogle} style={{ padding: "11px 18px", borderRadius: 10, border: "1px solid #dbe3ef", background: "#fff", color: "#334155", fontSize: 13.5, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>
                  Start free ->
                </button>
              </div>

              <div className="fade4" style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 16, padding: "26px 24px 22px", boxShadow: "0 4px 24px rgba(15,23,42,0.07)" }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a", marginBottom: 5 }}>Start free or sign in</div>
                <div style={{ fontSize: 12, color: "#94a3b8", marginBottom: 20 }}>For individual reps, new team members, and anyone already on a SalesLab AI workspace.</div>

                <button onClick={handleGoogle} disabled={loading} style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "center", gap: 10, padding: "11px 16px", borderRadius: 10, border: "1px solid #e2e8f0", background: "#fff", cursor: loading ? "not-allowed" : "pointer", fontSize: 13.5, fontWeight: 600, color: "#0f172a", fontFamily: "'Inter', sans-serif", marginBottom: 9, opacity: loading ? 0.7 : 1 }}>
                  <svg width="18" height="18" viewBox="0 0 48 48"><path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9 3.2l6.7-6.7C35.7 2.5 30.2 0 24 0 14.6 0 6.6 5.4 2.6 13.3l7.8 6.1C12.3 13.1 17.7 9.5 24 9.5z"/><path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v8.5h12.7c-.6 3-2.3 5.5-4.8 7.2l7.5 5.8c4.4-4 6.9-10 6.9-17z"/><path fill="#FBBC05" d="M10.4 28.6A14.6 14.6 0 019.5 24c0-1.6.3-3.1.9-4.6L2.6 13.3A23.9 23.9 0 000 24c0 3.8.9 7.4 2.6 10.6l7.8-6z"/><path fill="#34A853" d="M24 48c6.2 0 11.4-2 15.2-5.5l-7.5-5.8c-2 1.4-4.6 2.2-7.7 2.2-6.3 0-11.6-3.6-13.6-9.3l-7.8 6C6.6 42.6 14.6 48 24 48z"/></svg>
                  {loading ? "Connecting…" : "Continue with Google"}
                </button>

                <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "12px 0" }}>
                  <div style={{ flex: 1, height: 1, background: "#e2e8f0" }} />
                  <span style={{ fontSize: 11, color: "#94a3b8", fontWeight: 500 }}>or continue with email</span>
                  <div style={{ flex: 1, height: 1, background: "#e2e8f0" }} />
                </div>

                {!emailSent ? (
                  <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                    <input value={email} onChange={e => { setEmail(e.target.value); setAuthError(""); }} onKeyDown={e => e.key === "Enter" && handleEmail()} placeholder="Enter your email" style={{ flex: "1 1 220px", minWidth: 0, padding: "10px 13px", borderRadius: 9, border: `1px solid ${authError ? "#fca5a5" : "#e2e8f0"}`, fontSize: 13, fontFamily: "'Inter', sans-serif", background: "#f8fafc", color: "#0f172a", outline: "none" }} />
                    <button onClick={handleEmail} disabled={loading} style={{ flex: "1 1 220px", minWidth: 0, padding: "10px 16px", borderRadius: 9, border: "none", background: "#1e293b", color: "#fff", fontSize: 13, fontWeight: 600, cursor: loading ? "not-allowed" : "pointer", fontFamily: "'Inter', sans-serif", whiteSpace: "nowrap", opacity: loading ? 0.7 : 1 }}>Email me a sign-in link -&gt;</button>
                  </div>
                ) : (
                  <div style={{ padding: "12px", borderRadius: 9, background: "#f0fdf4", border: "1px solid #bbf7d0", textAlign: "center", fontSize: 13, color: "#16a34a", fontWeight: 500 }}>✓ Magic link sent — check your email!</div>
                )}

                {authError && <div style={{ marginTop: 10, padding: "9px 12px", borderRadius: 8, background: "#fef2f2", border: "1px solid #fecaca", fontSize: 12, color: "#dc2626", fontFamily: "'Inter', sans-serif" }}>{authError}</div>}
                <div style={{ textAlign: "center", fontSize: 11.5, color: "#64748b", marginTop: 12, lineHeight: 1.6 }}>
                  Already signed up before? Use the same email to log in.
                </div>


                <div style={{ textAlign: "center", fontSize: 11, color: "#94a3b8", marginTop: 14, lineHeight: 1.6 }}>
                  By continuing, you agree to our{" "}
                  <button onClick={() => { setActivePage("terms"); window.scrollTo(0, 0); }} style={{ color: "#64748b", textDecoration: "underline", background: "none", border: "none", cursor: "pointer", padding: 0, font: "inherit" }}>Terms of Service</button>
                  {" "}and{" "}
                  <button onClick={() => { setActivePage("privacy"); window.scrollTo(0, 0); }} style={{ color: "#64748b", textDecoration: "underline", background: "none", border: "none", cursor: "pointer", padding: 0, font: "inherit" }}>Privacy Policy</button>.
                </div>
                <div style={{ textAlign: "center", marginTop: 14 }}>
                  <a href="/salespage.html" style={{ fontSize: 13, color: "#3b82f6", textDecoration: "none", fontWeight: 500, fontFamily: "'Inter', sans-serif" }}>
                    See pricing, team plans, and enterprise options ->
                  </a>
                </div>
              </div>

              <div className="fade5" style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, marginTop: 20 }}>
                <div style={{ display: "flex" }}>
                  {["#1e293b","#3b82f6","#0891b2","#7c3aed","#dc2626"].map((c, i) => (
                    <div key={i} style={{ width: 24, height: 24, borderRadius: "50%", background: c, border: "2px solid #f8fafc", marginRight: -7, fontSize: 9, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center", color: "#fff" }}>{"JAMSR"[i]}</div>
                  ))}
                </div>
                <span style={{ fontSize: 12, color: "#94a3b8", marginLeft: 10 }}>
                  <span style={{ color: "#f59e0b" }}>★★★★★</span> &nbsp;Built for individual reps, teams, and growing sales orgs
                </span>
              </div>
            </div>
          </div>
        )}
      </div>

      <div style={{ borderTop: "1px solid #e2e8f0", background: "#fff", padding: "16px 32px", display: "flex", justifyContent: "center", gap: "clamp(16px, 4vw, 48px)", flexWrap: "wrap" }}>
        {["Rep practice", "Manager visibility", "Readiness scoring", "Coaching workflow"].map((f, i) => (
          <div key={i} style={{ fontSize: 12, color: "#64748b", fontWeight: 500, whiteSpace: "nowrap" }}>{f}</div>
        ))}
      </div>
      <div style={{ borderTop: "1px solid #f1f5f9", background: "#fff", padding: "10px 32px", display: "flex", justifyContent: "center", gap: 20, flexWrap: "wrap" }}>
        {[ ["Privacy Policy", "privacy"], ["Terms of Service", "terms"], ["Refund Policy", "refund"], ["Contact", "/contact.html"], ["About Us", "about"], ["FAQ", "faq"] ].map(([label, target]) => (
          String(target).startsWith("/")
            ? <a key={label} href={target} target="_blank" rel="noreferrer" style={{ fontSize: 11, color: "#94a3b8", textDecoration: "none", fontFamily: "'Inter', sans-serif" }}>{label}</a>
            : <button key={label} onClick={() => { setActivePage(target); window.scrollTo(0,0); }} style={{ fontSize: 11, color: "#94a3b8", textDecoration: "none", fontFamily: "'Inter', sans-serif", background: "none", border: "none", cursor: "pointer", padding: 0 }}>{label}</button>
        ))}
      </div>
    </div>
  );
}

function UpgradePrompt({ feature, onClose, onUpgrade }) {
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 200, background: "rgba(15,23,42,0.55)", backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div style={{ background: "#fff", borderRadius: 18, padding: "30px 28px", maxWidth: 400, width: "100%", boxShadow: "0 24px 64px rgba(0,0,0,0.18)", border: "1px solid #e2e8f0" }}>
        <style>{`@keyframes fadeUp { from { opacity:0; transform:translateY(12px); } to { opacity:1; transform:translateY(0); } }`}</style>
        <div style={{ textAlign: "center", marginBottom: 22 }}>
          <div style={{ width: 48, height: 48, borderRadius: 12, background: "#1e293b", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 22, margin: "0 auto 14px" }}>⚡</div>
          <div style={{ fontSize: 17, fontWeight: 800, color: "#0f172a", marginBottom: 6 }}>{feature || "Pro Feature"}</div>
          <div style={{ fontSize: 13, color: "#64748b", lineHeight: 1.6 }}>Unlock this and every other Pro feature for just <strong style={{ color: "#0f172a" }}>$29/mo</strong>.</div>
        </div>
        <button onClick={onUpgrade} style={{ width: "100%", padding: "12px", borderRadius: 10, border: "none", background: "#1e293b", color: "#fff", fontSize: 14, fontWeight: 700, cursor: "pointer", fontFamily: "'Inter', sans-serif", marginBottom: 9 }}>Upgrade to Pro — $29/mo →</button>
        <button onClick={onClose} style={{ width: "100%", padding: "10px", borderRadius: 10, background: "transparent", border: "1px solid #e2e8f0", color: "#94a3b8", fontSize: 13, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Maybe later</button>
        <div style={{ textAlign: "center", marginTop: 12, display: "flex", justifyContent: "center", gap: 16, flexWrap: "wrap" }}>
          {[["Privacy Policy", "privacy"], ["Terms", "terms"], ["Refund Policy", "refund"]].map(([label, target]) => (
            <button key={label} onClick={() => { setActivePage(target); setShowPaywall(false); window.scrollTo(0, 0); }} style={{ fontSize: 10, color: "#cbd5e1", textDecoration: "none", fontFamily: "'Inter', sans-serif", background: "none", border: "none", cursor: "pointer", padding: 0 }}>{label}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

function SubscriberBadge({ tier }) {
  if (tier === "pro") return (
    <div style={{ display: "flex", alignItems: "center", gap: 5, padding: "3px 10px", borderRadius: 20, background: "rgba(59,130,246,0.12)", border: "1px solid rgba(59,130,246,0.25)" }}>
      <div style={{ width: 5, height: 5, borderRadius: "50%", background: "#3b82f6" }} />
      <span style={{ fontSize: 10, color: "#3b82f6", fontWeight: 700, letterSpacing: "0.06em" }}>PRO</span>
    </div>
  );
  if (tier === "team") return (
    <div style={{ display: "flex", alignItems: "center", gap: 5, padding: "3px 10px", borderRadius: 20, background: "#1e293b", border: "1px solid #334155" }}>
      <div style={{ width: 5, height: 5, borderRadius: "50%", background: "#86efac" }} />
      <span style={{ fontSize: 10, color: "#d1fae5", fontWeight: 700, letterSpacing: "0.06em" }}>TEAM</span>
    </div>
  );
  return null;
}

// ─── Section Page Industry & Role Data ───────────────────────────────────────
function OwnerAccessPanel({ currentUser, onClose, onAccessUpdated }) {
  const [search, setSearch] = useState("");
  const [results, setResults] = useState([]);
  const [selectedUser, setSelectedUser] = useState(null);
  const [planName, setPlanName] = useState("free");
  const [status, setStatus] = useState("active");
  const [role, setRole] = useState("member");
  const [companyId, setCompanyId] = useState("");
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [deleteLabel, setDeleteLabel] = useState("Delete User");

  const loadUsers = async (query = "") => {
    setLoading(true);
    setError("");
    const { data, error } = await sbDB.rpc("owner_search_users", {
      search_email: query.trim() || null,
    });
    if (error) {
      setError(typeof error === "string" ? error : JSON.stringify(error));
      setResults([]);
      setLoading(false);
      return;
    }
    setResults(Array.isArray(data) ? data : []);
    setLoading(false);
  };

  useEffect(() => { loadUsers(""); }, []);

  const chooseUser = (user) => {
    setSelectedUser(user);
    setPlanName(user.plan_name || "free");
    setStatus(user.status || "active");
    setRole(user.role || "member");
    setCompanyId(user.company_id || "");
    setDeleteLabel("Delete User");
    setError("");
    setSuccess("");
  };

  const saveAccess = async (overrides = {}, successMessage) => {
    if (!selectedUser?.user_id) return false;
    setSaving(true);
    setError("");
    setSuccess("");
    const nextPlan = overrides.planName ?? planName;
    const nextStatus = overrides.status ?? status;
    const nextRole = overrides.role ?? role;
    const nextCompanyId = overrides.companyId ?? companyId;
    const { error } = await sbDB.rpc("owner_set_user_access", {
      target_user_id: selectedUser.user_id,
      new_plan_name: nextPlan,
      new_status: nextStatus,
      new_role: nextRole || null,
      new_company_id: (nextCompanyId || "").trim() || null,
    });
    if (error) {
      setError(typeof error === "string" ? error : JSON.stringify(error));
      setSaving(false);
      return false;
    }
    if (nextPlan === "team") {
      const { data: existingTeam, error: teamLookupError } = await sbDB.select("teams", { manager_id: selectedUser.user_id }, { single: true });
      if (teamLookupError) {
        setError(typeof teamLookupError === "string" ? teamLookupError : JSON.stringify(teamLookupError));
        setSaving(false);
        return false;
      }
      if (!existingTeam) {
        const defaultTeamName = ((selectedUser.email || "Team").split("@")[0] || "Team").replace(/[._-]+/g, " ").replace(/\b\w/g, c => c.toUpperCase()) + " Team";
        const { error: teamCreateError } = await sbDB.insert("teams", {
          manager_id: selectedUser.user_id,
          name: defaultTeamName,
          seat_limit: 10,
        });
        if (teamCreateError) {
          setError(typeof teamCreateError === "string" ? teamCreateError : JSON.stringify(teamCreateError));
          setSaving(false);
          return false;
        }
      }
    }
    setPlanName(nextPlan);
    setStatus(nextStatus);
    setRole(nextRole || "member");
    setCompanyId((nextCompanyId || "").trim());
    setSuccess(successMessage || `Updated ${selectedUser.email} to ${nextPlan} / ${nextStatus}.`);
    await loadUsers(search);
    onAccessUpdated?.();
    setSaving(false);
    return true;
  };

  const handleSave = async () => {
    await saveAccess();
  };

  const handleQuickPlan = async (nextPlan) => {
    if (!selectedUser?.user_id) return;
    const nextCompanyId = nextPlan === "team" ? companyId : "";
    await saveAccess(
      { planName: nextPlan, status: "active", companyId: nextCompanyId },
      `Set ${selectedUser.email} to ${nextPlan.toUpperCase()} access.`
    );
  };

  const handleRestrict = async () => {
    if (!selectedUser?.user_id) return;
    await saveAccess(
      { status: "suspended", planName: "free" },
      `Restricted ${selectedUser.email}. They can no longer use the app until reactivated.`
    );
  };

  const handleDelete = async () => {
    if (!selectedUser?.user_id) return;
    if (selectedUser.user_id === currentUser?.id) {
      setError("You can't delete your own owner account from this panel.");
      return;
    }
    const confirmed = window.confirm(`Delete ${selectedUser.email} from active access? This will downgrade them to Free and suspend the account until you restore it.`);
    if (!confirmed) return;
    setDeleteLabel("Deleting...");
    const ok = await saveAccess(
      { planName: "free", status: "suspended", role: "member", companyId: "" },
      `Deleted ${selectedUser.email} from active access. Their account is now suspended and removed from paid access.`
    );
    setDeleteLabel(ok ? "Deleted" : "Delete User");
  };

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 120, background: "rgba(15,23,42,0.45)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div style={{ width: "min(980px, 100%)", maxHeight: "90vh", overflow: "auto", background: "#ffffff", borderRadius: 18, border: "1px solid #e2e8f0", boxShadow: "0 24px 80px rgba(15,23,42,0.22)" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "22px 24px 16px", borderBottom: "1px solid #e2e8f0" }}>
            <div>
              <div style={{ fontSize: 18, fontWeight: 800, color: "#0f172a", marginBottom: 4 }}>Owner Access Control</div>
              <div style={{ fontSize: 12.5, color: "#64748b" }}>Signed in as {currentUser?.email}. Search a user, then assign Free, Pro, or Team access, restrict usage, or remove active access.</div>
            </div>
          <button onClick={onClose} style={{ border: "1px solid #e2e8f0", background: "#fff", color: "#64748b", borderRadius: 9, padding: "8px 12px", cursor: "pointer", fontSize: 12.5, fontWeight: 600 }}>Close</button>
        </div>

        <div style={{ padding: 24, display: "grid", gridTemplateColumns: "1.1fr 0.9fr", gap: 20 }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
              <input
                value={search}
                onChange={e => setSearch(e.target.value)}
                onKeyDown={e => { if (e.key === "Enter") loadUsers(search); }}
                placeholder="Search by email"
                style={{ flex: 1, padding: "11px 13px", borderRadius: 10, border: "1px solid #dbe3ee", fontSize: 13, outline: "none", background: "#f8fafc" }}
              />
              <button onClick={() => loadUsers(search)} disabled={loading} style={{ padding: "11px 14px", borderRadius: 10, border: "none", background: "#1e293b", color: "#fff", fontSize: 12.5, fontWeight: 700, cursor: "pointer", opacity: loading ? 0.7 : 1 }}>
                {loading ? "Searching..." : "Search"}
              </button>
            </div>

            <div style={{ border: "1px solid #e2e8f0", borderRadius: 14, overflow: "hidden" }}>
              <div style={{ display: "grid", gridTemplateColumns: "1.4fr 0.7fr 0.6fr 0.7fr", gap: 10, padding: "12px 14px", background: "#f8fafc", borderBottom: "1px solid #e2e8f0", fontSize: 10.5, fontWeight: 700, color: "#64748b", letterSpacing: "0.06em" }}>
                <div>USER</div>
                <div>PLAN</div>
                <div>ROLE</div>
                <div>STATUS</div>
              </div>
              <div>
                {results.length === 0 && (
                  <div style={{ padding: "18px 14px", fontSize: 12.5, color: "#94a3b8" }}>No users found.</div>
                )}
                {results.map((user, idx) => (
                  <button
                    key={user.user_id || idx}
                    onClick={() => chooseUser(user)}
                    style={{
                      width: "100%",
                      display: "grid",
                      gridTemplateColumns: "1.4fr 0.7fr 0.6fr 0.7fr",
                      gap: 10,
                      padding: "13px 14px",
                      border: "none",
                      borderBottom: idx === results.length - 1 ? "none" : "1px solid #f1f5f9",
                      background: selectedUser?.user_id === user.user_id ? "#eff6ff" : "#fff",
                      cursor: "pointer",
                      textAlign: "left"
                    }}
                  >
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 700, color: "#0f172a", overflow: "hidden", textOverflow: "ellipsis" }}>{user.email}</div>
                      <div style={{ fontSize: 10.5, color: "#94a3b8", marginTop: 3, overflow: "hidden", textOverflow: "ellipsis" }}>{user.user_id}</div>
                    </div>
                    <div style={{ fontSize: 12, color: "#1e293b", fontWeight: 600 }}>{(user.plan_name || "free").toUpperCase()}</div>
                    <div style={{ fontSize: 12, color: "#64748b" }}>{user.role}</div>
                    <div style={{ fontSize: 12, color: user.status === "active" ? "#16a34a" : "#dc2626", fontWeight: 600 }}>{user.status}</div>
                  </button>
                ))}
              </div>
            </div>
          </div>

          <div style={{ border: "1px solid #e2e8f0", borderRadius: 14, padding: 18, background: "#fcfdff" }}>
            <div style={{ fontSize: 11, fontWeight: 800, color: "#94a3b8", letterSpacing: "0.1em", marginBottom: 10 }}>EDIT ACCESS</div>
            {selectedUser ? (
              <>
                <div style={{ marginBottom: 16 }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>{selectedUser.email}</div>
                  <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 4 }}>{selectedUser.user_id}</div>
                </div>

                <div style={{ display: "grid", gap: 12 }}>
                  <div style={{ display: "grid", gap: 8 }}>
                    <span style={{ fontSize: 11, fontWeight: 700, color: "#475569" }}>Quick Controls</span>
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0, 1fr))", gap: 8 }}>
                      <button onClick={() => handleQuickPlan("free")} disabled={saving} style={{ padding: "10px 8px", borderRadius: 10, border: "1px solid #cbd5e1", background: planName === "free" && status === "active" ? "#eff6ff" : "#fff", color: "#1e293b", fontSize: 12, fontWeight: 700, cursor: "pointer" }}>Free</button>
                      <button onClick={() => handleQuickPlan("pro")} disabled={saving} style={{ padding: "10px 8px", borderRadius: 10, border: "1px solid #cbd5e1", background: planName === "pro" && status === "active" ? "#eff6ff" : "#fff", color: "#1e293b", fontSize: 12, fontWeight: 700, cursor: "pointer" }}>Pro</button>
                      <button onClick={() => handleQuickPlan("team")} disabled={saving} style={{ padding: "10px 8px", borderRadius: 10, border: "1px solid #cbd5e1", background: planName === "team" && status === "active" ? "#eff6ff" : "#fff", color: "#1e293b", fontSize: 12, fontWeight: 700, cursor: "pointer" }}>Team</button>
                    </div>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                      <button onClick={handleRestrict} disabled={saving} style={{ padding: "10px 8px", borderRadius: 10, border: "1px solid #fecaca", background: "#fff1f2", color: "#b91c1c", fontSize: 12, fontWeight: 700, cursor: "pointer" }}>Restrict User</button>
                      <button onClick={handleDelete} disabled={saving} style={{ padding: "10px 8px", borderRadius: 10, border: "1px solid #e2e8f0", background: "#0f172a", color: "#fff", fontSize: 12, fontWeight: 700, cursor: "pointer" }}>{saving && deleteLabel === "Deleting..." ? "Deleting..." : deleteLabel}</button>
                    </div>
                    <div style={{ fontSize: 11, color: "#94a3b8", lineHeight: 1.5 }}>Delete removes paid access and suspends the account from this panel. Full auth deletion would still require a backend admin function.</div>
                  </div>

                  <label style={{ display: "grid", gap: 6 }}>
                    <span style={{ fontSize: 11, fontWeight: 700, color: "#475569" }}>Plan</span>
                    <select value={planName} onChange={e => setPlanName(e.target.value)} style={{ padding: "11px 12px", borderRadius: 10, border: "1px solid #dbe3ee", fontSize: 13, background: "#fff" }}>
                      <option value="free">Free</option>
                      <option value="pro">Pro</option>
                      <option value="team">Team</option>
                      <option value="enterprise">Enterprise</option>
                    </select>
                  </label>

                  <label style={{ display: "grid", gap: 6 }}>
                    <span style={{ fontSize: 11, fontWeight: 700, color: "#475569" }}>Status</span>
                    <select value={status} onChange={e => setStatus(e.target.value)} style={{ padding: "11px 12px", borderRadius: 10, border: "1px solid #dbe3ee", fontSize: 13, background: "#fff" }}>
                      <option value="active">Active</option>
                      <option value="inactive">Inactive</option>
                      <option value="suspended">Suspended</option>
                    </select>
                  </label>

                  <label style={{ display: "grid", gap: 6 }}>
                    <span style={{ fontSize: 11, fontWeight: 700, color: "#475569" }}>Role</span>
                    <select value={role} onChange={e => setRole(e.target.value)} style={{ padding: "11px 12px", borderRadius: 10, border: "1px solid #dbe3ee", fontSize: 13, background: "#fff" }}>
                      <option value="member">Member</option>
                      <option value="owner">Owner</option>
                    </select>
                  </label>

                  <label style={{ display: "grid", gap: 6 }}>
                    <span style={{ fontSize: 11, fontWeight: 700, color: "#475569" }}>Company ID</span>
                    <input value={companyId} onChange={e => setCompanyId(e.target.value)} placeholder="Optional UUID" style={{ padding: "11px 12px", borderRadius: 10, border: "1px solid #dbe3ee", fontSize: 13, background: "#fff" }} />
                  </label>
                </div>

                {error && <div style={{ marginTop: 14, padding: "10px 12px", borderRadius: 10, background: "#fef2f2", border: "1px solid #fecaca", color: "#dc2626", fontSize: 12 }}>{error}</div>}
                {success && <div style={{ marginTop: 14, padding: "10px 12px", borderRadius: 10, background: "#f0fdf4", border: "1px solid #bbf7d0", color: "#15803d", fontSize: 12 }}>{success}</div>}

                <button onClick={handleSave} disabled={saving} style={{ width: "100%", marginTop: 16, padding: "12px", borderRadius: 10, border: "none", background: "#0f172a", color: "#fff", fontSize: 13.5, fontWeight: 700, cursor: "pointer", opacity: saving ? 0.7 : 1 }}>
                  {saving ? "Saving..." : "Save access changes"}
                </button>
              </>
            ) : (
              <div style={{ fontSize: 12.5, color: "#94a3b8", lineHeight: 1.7 }}>Choose a user from the left to edit their plan, status, role, or company.</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

const SECTION_INDUSTRIES = [
  { id: "kitchen",     label: "Kitchen Remodeling",        group: "Home Improvement" },
  { id: "flooring",    label: "Flooring",                  group: "Home Improvement" },
  { id: "roofing",     label: "Roofing",                   group: "Home Improvement" },
  { id: "windows",     label: "Windows & Doors",           group: "Home Improvement" },
  { id: "hvac",        label: "HVAC",                      group: "Home Improvement" },
  { id: "solar",       label: "Solar",                     group: "Home Improvement" },
  { id: "construction",label: "Construction Services",     group: "Home Improvement" },
  { id: "realestate",  label: "Real Estate",               group: "Real Estate & Property" },
  { id: "commercial",  label: "Commercial Real Estate",    group: "Real Estate & Property" },
  { id: "auto",        label: "Automotive Sales",          group: "Automotive" },
  { id: "furniture",   label: "Furniture Sales",           group: "Retail High-Ticket" },
  { id: "mattress",    label: "Mattress Sales",            group: "Retail High-Ticket" },
  { id: "appliance",   label: "Appliance Sales",           group: "Retail High-Ticket" },
  { id: "saas",        label: "SaaS / Software",           group: "Business & Technology" },
  { id: "enterprise",  label: "Enterprise Software",       group: "Business & Technology" },
  { id: "b2b",         label: "B2B / Professional Services", group: "Business & Technology" },
  { id: "consulting",  label: "Consulting / Agencies",     group: "Business & Technology" },
  { id: "financial",   label: "Financial Services",        group: "Financial" },
  { id: "insurance",   label: "Insurance",                 group: "Financial" },
  { id: "remote",      label: "Remote Closing",            group: "Other" },
  { id: "general",     label: "General",                   group: "Other" },
  { id: "other",       label: "Other",                     group: "Other" },
];

const SECTION_ROLES = [
  { id: "inhome",      label: "In-Home Sales Rep" },
  { id: "ae",          label: "Account Executive" },
  { id: "sdr",         label: "SDR / BDR" },
  { id: "remote_closer", label: "Remote Closer" },
  { id: "closer",      label: "Closer" },
  { id: "consultant",  label: "Sales Consultant" },
  { id: "realtor",     label: "Real Estate Agent" },
  { id: "carsales",    label: "Car Sales Consultant" },
  { id: "advisor",     label: "Financial Advisor" },
  { id: "insurance_agent", label: "Insurance Agent" },
  { id: "manager",     label: "Sales Manager" },
  { id: "founder",     label: "Founder / Owner" },
  { id: "other",       label: "Other" },
];

const SECTION_ENVS = [
  { id: "inhome",   label: "In-Home" },
  { id: "showroom", label: "Showroom" },
  { id: "phone",    label: "Phone Sales" },
  { id: "zoom",     label: "Video / Zoom" },
  { id: "field",    label: "Field Sales" },
  { id: "remote",   label: "Remote" },
  { id: "other",    label: "Other" },
];

// Build a context prefix that personalizes auto-prompts based on selected industry/role/env
function buildSectionContext(industry, role, env) {
  const ind = SECTION_INDUSTRIES.find(i => i.id === industry);
  const rol = SECTION_ROLES.find(r => r.id === role);
  const envi = SECTION_ENVS.find(e => e.id === env);
  if (!ind && !rol && !envi) return "";
  const parts = [];
  if (ind) parts.push(`Industry: ${ind.label}`);
  if (rol) parts.push(`Role: ${rol.label}`);
  if (envi) parts.push(`Environment: ${envi.label}`);
  return `[${parts.join(" | ")}] `;
}

// Personalize a subsection prompt with industry/role/env context
function personalizeSectionPrompt(prompt, industry, role, env) {
  const ctx = buildSectionContext(industry, role, env);
  if (!ctx) return prompt;
  if (prompt.trim().endsWith(":")) return prompt + " " + ctx.trim();
  return ctx + prompt;
}


// ─── Industry Benchmarks for Profit Engine ────────────────────────────────────
const INDUSTRY_BENCHMARKS = {
  kitchen:      { closeRate: 35, avgDeal: 18000, commission: 8,  label: "Kitchen Remodeling" },
  flooring:     { closeRate: 40, avgDeal: 6500,  commission: 10, label: "Flooring" },
  roofing:      { closeRate: 30, avgDeal: 12000, commission: 8,  label: "Roofing" },
  windows:      { closeRate: 32, avgDeal: 9500,  commission: 9,  label: "Windows & Doors" },
  hvac:         { closeRate: 38, avgDeal: 7500,  commission: 8,  label: "HVAC" },
  solar:        { closeRate: 22, avgDeal: 28000, commission: 6,  label: "Solar" },
  construction: { closeRate: 28, avgDeal: 35000, commission: 5,  label: "Construction" },
  realestate:   { closeRate: 18, avgDeal: 12000, commission: 2.5,label: "Real Estate" },
  commercial:   { closeRate: 15, avgDeal: 45000, commission: 2,  label: "Commercial Real Estate" },
  auto:         { closeRate: 55, avgDeal: 3500,  commission: 5,  label: "Automotive" },
  furniture:    { closeRate: 45, avgDeal: 4500,  commission: 7,  label: "Furniture" },
  mattress:     { closeRate: 50, avgDeal: 2200,  commission: 8,  label: "Mattress" },
  appliance:    { closeRate: 48, avgDeal: 1800,  commission: 6,  label: "Appliance" },
  saas:         { closeRate: 20, avgDeal: 18000, commission: 8,  label: "SaaS / Software" },
  enterprise:   { closeRate: 12, avgDeal: 85000, commission: 6,  label: "Enterprise Software" },
  b2b:          { closeRate: 22, avgDeal: 22000, commission: 7,  label: "B2B Services" },
  consulting:   { closeRate: 25, avgDeal: 15000, commission: 10, label: "Consulting" },
  financial:    { closeRate: 28, avgDeal: 8500,  commission: 4,  label: "Financial Services" },
  insurance:    { closeRate: 30, avgDeal: 3200,  commission: 12, label: "Insurance" },
  remote:       { closeRate: 20, avgDeal: 5000,  commission: 15, label: "Remote Closing" },
  general:      { closeRate: 25, avgDeal: 10000, commission: 8,  label: "General" },
  other:        { closeRate: 25, avgDeal: 10000, commission: 8,  label: "Other" },
};

// ─── Profit Engine Component ──────────────────────────────────────────────────
function ProfitEngine({ onExit, isPro, onUpgrade }) {
  const [industry, setIndustry] = useState("");
  const [leads, setLeads] = useState("");
  const [closeRate, setCloseRate] = useState("");
  const [avgDeal, setAvgDeal] = useState("");
  const [commission, setCommission] = useState("");
  const [calculated, setCalculated] = useState(false);

  const benchmark = INDUSTRY_BENCHMARKS[industry] || null;

  const num = (v) => parseFloat(v) || 0;

  // Current performance
  const currentDeals = Math.floor(num(leads) * (num(closeRate) / 100));
  const currentRevenue = currentDeals * num(avgDeal);
  const currentCommission = currentRevenue * (num(commission) / 100);

  // Target = benchmark + 15% uplift to always show meaningful improvement potential
  const TARGET_UPLIFT = 1.15;
  const targetCloseRate = benchmark ? benchmark.closeRate * TARGET_UPLIFT : 0;
  const targetAvgDeal   = benchmark ? benchmark.avgDeal   * TARGET_UPLIFT : 0;
  const targetCommission = benchmark ? benchmark.commission : 0;

  const benchmarkDeals      = benchmark ? Math.floor(num(leads) * (benchmark.closeRate / 100)) : 0;
  const benchmarkRevenue    = benchmark ? benchmarkDeals * benchmark.avgDeal : 0;
  const benchmarkCommission = benchmark ? benchmarkRevenue * (benchmark.commission / 100) : 0;

  // Improved = what they could achieve with SalesLab training (always above their current)
  const improvedCloseRate  = Math.max(num(closeRate) * 1.18, targetCloseRate);
  const improvedAvgDeal    = Math.max(num(avgDeal)   * 1.12, targetAvgDeal);
  const improvedDeals      = benchmark ? Math.floor(num(leads) * (improvedCloseRate / 100)) : 0;
  const improvedRevenue    = benchmark ? improvedDeals * improvedAvgDeal : 0;
  const improvedCommission = benchmark ? improvedRevenue * (targetCommission / 100) : 0;

  // Profit gap = difference between improved and current (always positive)
  const monthlyGap = Math.max(improvedCommission - currentCommission, currentCommission * 0.2);
  const annualGap  = monthlyGap * 12;

  // Performance score — always shows room to grow (capped at 89 so there's always upside shown)
  const closeScore        = benchmark ? Math.min(89, Math.round((num(closeRate) / improvedCloseRate) * 100)) : 0;
  const dealScore         = benchmark ? Math.min(89, Math.round((num(avgDeal)   / improvedAvgDeal)   * 100)) : 0;
  const salesPotentialScore = benchmark ? Math.min(89, Math.round((closeScore * 0.6) + (dealScore * 0.4))) : 0;

  // Performance meter % vs improved target (always < 100 so there's always upside)
  const performancePct = benchmark ? Math.min(89, Math.round((currentRevenue / improvedRevenue) * 100)) : 0;

  const canCalculate = industry && num(leads) > 0 && num(closeRate) > 0 && num(avgDeal) > 0 && num(commission) > 0;

  const fmt = (n) => n >= 1000 ? "$" + (n >= 1000000 ? (n/1000000).toFixed(1) + "M" : Math.round(n/1000) + "k") : "$" + Math.round(n);

  // Training recommendations based on weakest metric
  const getRecommendations = () => {
    if (!benchmark) return [];
    const recs = [];
    if (num(closeRate) < benchmark.closeRate) recs.push({ label: "Objection Handling", section: 1, reason: "Your close rate is below industry average — sharpen your objection responses." });
    if (num(avgDeal) < benchmark.avgDeal) recs.push({ label: "Discovery Questions", section: 3, reason: "Improving discovery helps you identify higher-value opportunities." });
    if (recs.length === 0) recs.push({ label: "Advanced Coaching", section: 6, reason: "You\'re performing well — level up with advanced deal coaching." });
    return recs.slice(0, 2);
  };

  const inputStyle = {
    width: "100%", padding: "10px 12px", borderRadius: 8,
    border: "1px solid #e2e8f0", background: "#f8fafc",
    fontSize: 13, color: "#1e293b", fontFamily: "'Inter', sans-serif",
    outline: "none", boxSizing: "border-box",
  };

  const labelStyle = { fontSize: 11, fontWeight: 600, color: "#475569", marginBottom: 5, display: "block" };

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 150, background: "#f8fafc", display: "flex", flexDirection: "column", fontFamily: "'Inter', sans-serif" }}>
      {/* Header */}
      <div style={{ padding: "0 20px", height: 56, background: "#ffffff", borderBottom: "1px solid #e2e8f0", display: "flex", alignItems: "center", justifyContent: "space-between", flexShrink: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ fontSize: 18 }}>💰</span>
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>Profit Engine</div>
            <div style={{ fontSize: 10, color: "#94a3b8", letterSpacing: "0.1em" }}>CALCULATE YOUR EARNINGS POTENTIAL</div>
          </div>
        </div>
        <button onClick={onExit} style={{ background: "transparent", border: "1px solid #e2e8f0", color: "#64748b", borderRadius: 6, padding: "5px 14px", fontSize: 11, cursor: "pointer" }}>← Back to Chat</button>
      </div>

      {/* Body */}
      <div style={{ flex: 1, overflowY: "auto", padding: "24px 20px" }}>
        <div style={{ maxWidth: 600, margin: "0 auto" }}>

          {/* Intro */}
          <div style={{ marginBottom: 24, padding: "16px 20px", borderRadius: 12, background: "#fff", border: "0.5px solid #D1D9E6" }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: "#0F172A", marginBottom: 4 }}>See exactly how much more you could be earning</div>
            <div style={{ fontSize: 12, color: "#64748b", lineHeight: 1.6 }}>Enter your current numbers and Profit Engine compares them to industry benchmarks — then shows you the gap.</div>
          </div>

          {/* Input Form */}
          <div style={{ background: "#ffffff", borderRadius: 12, border: "1px solid #e2e8f0", padding: "20px", marginBottom: 20 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 16 }}>YOUR NUMBERS</div>

            <div style={{ marginBottom: 14 }}>
              <label style={labelStyle}>Industry</label>
              <select value={industry} onChange={e => { setIndustry(e.target.value); setCalculated(false); }} style={{ ...inputStyle, appearance: "none", cursor: "pointer" }}>
                <option value="">— Select your industry —</option>
                {[
                  ["Home Improvement", ["kitchen","flooring","roofing","windows","hvac","solar","construction"]],
                  ["Real Estate", ["realestate","commercial"]],
                  ["Automotive & Retail", ["auto","furniture","mattress","appliance"]],
                  ["B2B & Tech", ["saas","enterprise","b2b","consulting"]],
                  ["Financial", ["financial","insurance"]],
                  ["Other", ["remote","general","other"]],
                ].map(([group, ids]) => (
                  <optgroup key={group} label={group}>
                    {ids.map(id => <option key={id} value={id}>{INDUSTRY_BENCHMARKS[id].label}</option>)}
                  </optgroup>
                ))}
              </select>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 14 }}>
              <div>
                <label style={labelStyle}>Leads Per Month</label>
                <input type="number" value={leads} onChange={e => { setLeads(e.target.value); setCalculated(false); }} placeholder="e.g. 30" style={inputStyle} />
              </div>
              <div>
                <label style={labelStyle}>Your Close Rate (%)</label>
                <input type="number" value={closeRate} onChange={e => { setCloseRate(e.target.value); setCalculated(false); }} placeholder="e.g. 20" style={inputStyle} />
              </div>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 20 }}>
              <div>
                <label style={labelStyle}>Average Deal Size ($)</label>
                <input type="number" value={avgDeal} onChange={e => { setAvgDeal(e.target.value); setCalculated(false); }} placeholder="e.g. 10000" style={inputStyle} />
              </div>
              <div>
                <label style={labelStyle}>Your Commission (%)</label>
                <input type="number" value={commission} onChange={e => { setCommission(e.target.value); setCalculated(false); }} placeholder="e.g. 8" style={inputStyle} />
              </div>
            </div>

            <button onClick={() => canCalculate && setCalculated(true)} disabled={!canCalculate} style={{ width: "100%", padding: "13px", borderRadius: 10, border: "none", background: canCalculate ? "#1D4ED8" : "#E2E8F0", color: canCalculate ? "#fff" : "#94a3b8", fontSize: 14, fontWeight: 700, cursor: canCalculate ? "pointer" : "not-allowed", fontFamily: "'Inter', sans-serif" }}>
              Calculate My Profit Potential →
            </button>
          </div>

          {/* Results */}
          {calculated && benchmark && (
            <>
              {/* Current Performance */}
              <div style={{ background: "#ffffff", borderRadius: 12, border: "1px solid #e2e8f0", padding: "20px", marginBottom: 16 }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 16 }}>YOUR CURRENT PERFORMANCE</div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginBottom: 20 }}>
                  {[
                    { label: "Deals / Month", val: currentDeals, color: "#0f172a" },
                    { label: "Monthly Revenue", val: fmt(currentRevenue), color: "#0f172a" },
                    { label: "Monthly Commission", val: fmt(currentCommission), color: "#16a34a" },
                  ].map((s, i) => (
                    <div key={i} style={{ padding: "12px", borderRadius: 10, background: "#f8fafc", border: "1px solid #e2e8f0", textAlign: "center" }}>
                      <div style={{ fontSize: i === 0 ? 22 : 18, fontWeight: 800, color: s.color, marginBottom: 3 }}>{s.val}</div>
                      <div style={{ fontSize: 10, color: "#94a3b8", fontWeight: 600 }}>{s.label}</div>
                    </div>
                  ))}
                </div>

                {/* Performance Meter */}
                <div style={{ marginBottom: 6 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
                    <div style={{ fontSize: 11, fontWeight: 700, color: "#475569" }}>Performance vs {benchmark.label} Training Target</div>
                    <div style={{ fontSize: 11, fontWeight: 700, color: performancePct >= 80 ? "#16a34a" : performancePct >= 50 ? "#f59e0b" : "#dc2626" }}>{performancePct}%</div>
                  </div>
                  <div style={{ height: 10, background: "#f1f5f9", borderRadius: 10, overflow: "hidden" }}>
                    <div style={{ height: "100%", width: `${performancePct}%`, borderRadius: 10, background: performancePct >= 80 ? "linear-gradient(90deg, #16a34a, #22c55e)" : performancePct >= 50 ? "linear-gradient(90deg, #f59e0b, #fbbf24)" : "linear-gradient(90deg, #dc2626, #ef4444)", transition: "width 0.8s ease" }} />
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", marginTop: 5 }}>
                    <div style={{ fontSize: 10, color: "#94a3b8" }}>You</div>
                    <div style={{ fontSize: 10, color: "#94a3b8" }}>Industry Average</div>
                  </div>
                </div>
              </div>

              {/* Improved Target */}
              <div style={{ background: "#ffffff", borderRadius: 12, border: "1px solid #e2e8f0", padding: "20px", marginBottom: 16 }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 16 }}>WITH SALESLAB TRAINING — YOUR TARGET</div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
                  {[
                    { label: "Target Close Rate", val: Math.round(improvedCloseRate) + "%", yours: Math.round(num(closeRate)) + "%" },
                    { label: "Target Deal Size",  val: fmt(improvedAvgDeal),              yours: fmt(num(avgDeal)) },
                    { label: "Target Commission", val: fmt(improvedCommission) + "/mo",   yours: fmt(currentCommission) + "/mo" },
                  ].map((s, i) => (
                    <div key={i} style={{ padding: "12px", borderRadius: 10, background: "#f0fdf4", border: "1px solid #bbf7d0", textAlign: "center" }}>
                      <div style={{ fontSize: 16, fontWeight: 800, color: "#16a34a", marginBottom: 2 }}>{s.val}</div>
                      <div style={{ fontSize: 10, color: "#94a3b8", marginBottom: 4 }}>{s.label}</div>
                      <div style={{ fontSize: 10, color: "#64748b", fontWeight: 600 }}>Now: {s.yours}</div>
                    </div>
                  ))}
                </div>
              </div>

              {/* PROFIT GAP — blurred for free users */}
              <div style={{ position: "relative", marginBottom: 16 }}>
                <div style={{ background: "#ffffff", borderRadius: 12, border: "1px solid #e2e8f0", padding: "20px", filter: isPro ? "none" : "blur(6px)", userSelect: isPro ? "auto" : "none", pointerEvents: isPro ? "auto" : "none" }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 16 }}>YOUR PROFIT GAP</div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 16 }}>
                    <div style={{ padding: "16px", borderRadius: 10, background: "#fef2f2", border: "1px solid #fecaca", textAlign: "center" }}>
                      <div style={{ fontSize: 24, fontWeight: 800, color: "#dc2626", marginBottom: 3 }}>{fmt(monthlyGap)}</div>
                      <div style={{ fontSize: 11, color: "#dc2626", fontWeight: 600 }}>Monthly Gap</div>
                      <div style={{ fontSize: 10, color: "#94a3b8", marginTop: 2 }}>left on the table</div>
                    </div>
                    <div style={{ padding: "16px", borderRadius: 10, background: "#f0fdf4", border: "1px solid #bbf7d0", textAlign: "center" }}>
                      <div style={{ fontSize: 24, fontWeight: 800, color: "#16a34a", marginBottom: 3 }}>{fmt(annualGap)}</div>
                      <div style={{ fontSize: 11, color: "#16a34a", fontWeight: 600 }}>Annual Potential</div>
                      <div style={{ fontSize: 10, color: "#94a3b8", marginTop: 2 }}>if you hit average</div>
                    </div>
                  </div>
                  {/* Sales Potential Score */}
                  <div style={{ padding: "14px 16px", borderRadius: 10, background: "#EFF6FF", border: "0.5px solid #BFDBFE", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <div>
                      <div style={{ fontSize: 11, fontWeight: 700, color: "#1D4ED8", letterSpacing: "0.1em", marginBottom: 4 }}>SALES POTENTIAL SCORE</div>
                      <div style={{ fontSize: 11, color: "#1E3A8A", lineHeight: 1.5 }}>Based on your close rate and deal size vs industry</div>
                    </div>
                    <div style={{ textAlign: "center", flexShrink: 0 }}>
                      <div style={{ fontSize: 36, fontWeight: 800, color: salesPotentialScore >= 80 ? "#16A34A" : salesPotentialScore >= 50 ? "#1D4ED8" : "#1D4ED8" }}>{salesPotentialScore}</div>
                      <div style={{ fontSize: 9, color: "#475569", fontWeight: 600 }}>/100</div>
                    </div>
                  </div>
                </div>

                {/* Upgrade overlay for free users */}
                {!isPro && (
                  <div style={{ position: "absolute", inset: 0, borderRadius: 12, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", background: "rgba(248,250,252,0.7)", backdropFilter: "blur(2px)", gap: 10 }}>
                    <div style={{ fontSize: 24 }}>🔒</div>
                    <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a", textAlign: "center" }}>Unlock Your Full Profit Gap</div>
                    <div style={{ fontSize: 12, color: "#64748b", textAlign: "center", maxWidth: 240, lineHeight: 1.5 }}>See exactly how much you're leaving on the table and your Sales Potential Score.</div>
                    <button onClick={onUpgrade} style={{ padding: "10px 24px", borderRadius: 10, background: "#0f172a", border: "none", color: "#fff", fontSize: 13, fontWeight: 700, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Upgrade to Pro →</button>
                  </div>
                )}
              </div>

              {/* Guide CTA */}
              <div style={{ background: "#eff6ff", border: "1.5px solid #bfdbfe", borderRadius: 14, padding: "20px 20px 18px", marginBottom: 16 }}>
                <div style={{ fontSize: 9, fontWeight: 700, color: "#2563eb", letterSpacing: "0.15em", marginBottom: 10, fontFamily: "'Inter', sans-serif" }}>FREE GUIDE</div>
                <div style={{ fontSize: 15, fontWeight: 800, color: "#0f172a", lineHeight: 1.25, marginBottom: 8, fontFamily: "'Inter', sans-serif", letterSpacing: "-0.01em" }}>Want to close that gap<br/>in 30 days?</div>
                <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
                  {[["Week 1","Baseline & objections"], ["Week 2","Roleplay & personas"], ["Week 3–4","Score & compete"]].map(([wk, lbl]) => (
                    <div key={wk} style={{ flex: 1, background: "#ffffff", border: "1px solid #bfdbfe", borderRadius: 8, padding: "8px 8px 7px", textAlign: "center" }}>
                      <div style={{ fontSize: 10, fontWeight: 700, color: "#2563eb", fontFamily: "'Inter', sans-serif", marginBottom: 2 }}>{wk}</div>
                      <div style={{ fontSize: 9, color: "#64748b", fontFamily: "'Inter', sans-serif", lineHeight: 1.3 }}>{lbl}</div>
                    </div>
                  ))}
                </div>
                <div style={{ fontSize: 11, color: "#64748b", lineHeight: 1.55, marginBottom: 14, fontFamily: "'Inter', sans-serif" }}>
                  Step-by-step training plan + the ROI math that shows how the app pays for itself on the first extra close.
                </div>
                <a href="/guide.html" target="_blank" rel="noreferrer" style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 6, width: "100%", padding: "11px", borderRadius: 9, background: "#0f172a", color: "#fff", fontSize: 13, fontWeight: 700, textDecoration: "none", fontFamily: "'Inter', sans-serif", boxSizing: "border-box" }}>
                  Get the free 30-day guide
                  <svg width="13" height="13" viewBox="0 0 16 16" fill="none"><path d="M3 8h10M9 4l4 4-4 4" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </a>
              </div>

              {/* Training Recommendations — blurred for free */}
              {isPro && (
                <div style={{ background: "#ffffff", borderRadius: 12, border: "1px solid #e2e8f0", padding: "20px", marginBottom: 16 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 16 }}>RECOMMENDED TRAINING</div>
                  <div style={{ fontSize: 12, color: "#64748b", marginBottom: 14, lineHeight: 1.6 }}>Based on your numbers, these are the highest-impact areas to improve your earnings:</div>
                  {getRecommendations().map((rec, i) => (
                    <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", borderRadius: 10, background: "#f8fafc", border: "1px solid #e2e8f0", marginBottom: 8 }}>
                      <span style={{ fontSize: 16 }}>🎯</span>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: "#0f172a", marginBottom: 2 }}>{rec.label}</div>
                        <div style={{ fontSize: 11, color: "#64748b" }}>{rec.reason}</div>
                      </div>
                      <button onClick={() => { onExit(); }} style={{ padding: "6px 14px", borderRadius: 7, background: "#1D4ED8", border: "none", color: "#fff", fontSize: 11, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif", whiteSpace: "nowrap" }}>Train Now →</button>
                    </div>
                  ))}
                </div>
              )}

              {/* Run another */}
              <button onClick={() => { setCalculated(false); setIndustry(""); setLeads(""); setCloseRate(""); setAvgDeal(""); setCommission(""); }} style={{ width: "100%", padding: "12px", borderRadius: 10, background: "transparent", border: "1px solid #e2e8f0", color: "#64748b", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif", marginBottom: 24 }}>
                Run Another Calculation
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Sales IQ Assessment ───────────────────────────────────────────────────────

const SIQ_OTHER_ROLE = { id: "other", name: "Other / Not listed", desc: "General sales scenarios", isOther: true };

const SIQ_INDUSTRIES = [
  { id: "tech", icon: "💻", name: "Tech / SaaS", desc: "Software, platforms, cloud", roles: [
    { id: "ae", name: "Account Executive", desc: "Full-cycle, closing deals" },
    { id: "sdr", name: "SDR", desc: "Inbound lead qualification" },
    { id: "bdr", name: "BDR", desc: "Outbound prospecting" },
    { id: "csm", name: "Customer Success", desc: "Expansion & retention" },
    { id: "se", name: "Sales Engineer", desc: "Technical pre-sales" },
    { id: "smb", name: "SMB Rep", desc: "Small business sales" },
  ]},
  { id: "inhome", icon: "🏠", name: "In-Home Services", desc: "Solar, Roofing, HVAC, Remodeling", roles: [
    { id: "solar", name: "Solar Consultant", desc: "Residential solar sales" },
    { id: "roofing", name: "Roofing Rep", desc: "Storm & retail roofing" },
    { id: "hvac", name: "HVAC Specialist", desc: "Heating & cooling sales" },
    { id: "kitchen", name: "Kitchen Remodeling", desc: "Custom kitchen sales" },
    { id: "bath", name: "Bathroom Remodeling", desc: "Bath & shower remodels" },
    { id: "windows", name: "Windows & Doors", desc: "Home improvement sales" },
    { id: "pest", name: "Pest Control", desc: "D2D & appointment close" },
    { id: "security", name: "Home Security", desc: "Alarm & smart home" },
  ]},
  { id: "insurance", icon: "🛡️", name: "Insurance & Financial", desc: "Life, P&C, wealth, lending", roles: [
    { id: "life", name: "Life Insurance", desc: "Term, whole, indexed" },
    { id: "health", name: "Health Insurance", desc: "Individual & group plans" },
    { id: "pa", name: "P&C Agent", desc: "Auto, home, commercial" },
    { id: "fa", name: "Financial Advisor", desc: "Wealth & retirement" },
    { id: "mortgage", name: "Mortgage Officer", desc: "Home lending & refi" },
    { id: "annuity", name: "Annuity Specialist", desc: "Retirement income sales" },
  ]},
  { id: "realestate", icon: "🏡", name: "Real Estate", desc: "Residential, commercial, rentals", roles: [
    { id: "buyer", name: "Buyer's Agent", desc: "Representing buyers" },
    { id: "listing", name: "Listing Agent", desc: "Representing sellers" },
    { id: "commercial", name: "Commercial Agent", desc: "Office, retail, industrial" },
    { id: "pm", name: "Property Manager", desc: "Leasing & renewals" },
    { id: "newdev", name: "New Development", desc: "New construction sales" },
    { id: "invest", name: "Investment Sales", desc: "REI & multi-family" },
  ]},
  { id: "auto", icon: "🚗", name: "Auto Sales", desc: "New, used, F&I, fleet", roles: [
    { id: "new", name: "New Car Sales", desc: "Franchise dealership" },
    { id: "used", name: "Used Car Sales", desc: "Pre-owned & CPO" },
    { id: "fi", name: "F&I Manager", desc: "Finance & insurance" },
    { id: "fleet", name: "Fleet Sales", desc: "Commercial fleet deals" },
    { id: "bdc", name: "BDC Rep", desc: "Inbound leads & appts" },
    { id: "rv", name: "RV / Power Sports", desc: "Specialty vehicle sales" },
  ]},
  { id: "retail", icon: "🛍️", name: "Retail & B2C", desc: "Consumer, e-comm, luxury", roles: [
    { id: "luxury", name: "Luxury Retail", desc: "High-ticket consumer" },
    { id: "ecomm", name: "E-Commerce Sales", desc: "Online & phone sales" },
    { id: "showroom", name: "Showroom Sales", desc: "Furniture, appliances" },
    { id: "b2c", name: "B2C Account Rep", desc: "Direct consumer sales" },
    { id: "telecom", name: "Telecom Sales", desc: "Mobile & internet plans" },
    { id: "travel", name: "Travel & Leisure", desc: "Vacations, timeshare" },
  ]},
  { id: "staffing", icon: "🤝", name: "Staffing & Recruiting", desc: "Temp, perm, exec search", roles: [
    { id: "recruiter", name: "Recruiter", desc: "Candidate placement" },
    { id: "bdev", name: "Business Dev", desc: "Client acquisition" },
    { id: "exec", name: "Exec Search", desc: "C-suite & director roles" },
    { id: "temp", name: "Temp Staffing", desc: "Contract & light industrial" },
    { id: "msp", name: "MSP Sales", desc: "Managed service programs" },
    { id: "hr", name: "HR Solutions", desc: "HR outsourcing & PEO" },
  ]},
  { id: "marketing", icon: "📣", name: "Marketing & Agency", desc: "Digital, media, creative", roles: [
    { id: "digital", name: "Digital Agency", desc: "SEO, PPC, social media" },
    { id: "media", name: "Media Sales", desc: "TV, radio, print, OOH" },
    { id: "adtech", name: "AdTech Sales", desc: "Programmatic & DSPs" },
    { id: "pr", name: "PR & Comms", desc: "Reputation & earned media" },
    { id: "events", name: "Events & Sponsorship", desc: "Live & virtual events" },
    { id: "creative", name: "Creative Services", desc: "Design, video, branding" },
  ]},
  { id: "other", icon: "✳️", name: "Other", desc: "Any other sales role", roles: [
    { id: "med", name: "Medical / Pharma", desc: "Healthcare sales" },
    { id: "gov", name: "Government Sales", desc: "Public sector & grants" },
    { id: "nonprofit", name: "Nonprofit / Fundraising", desc: "Major gifts & grants" },
    { id: "mfg", name: "Manufacturing", desc: "Industrial & distribution" },
    { id: "food", name: "Food & Beverage", desc: "Wholesale & distribution" },
    { id: "gen", name: "General Sales", desc: "Mixed or uncategorized" },
  ]},
];

const SIQ_FAKE_LB = [
  { name: "Marcus T.", company: "Salesforce AE", score: 96 },
  { name: "Jordan W.", company: "HubSpot SDR", score: 91 },
  { name: "Priya M.", company: "Gong AE", score: 88 },
  { name: "Devon K.", company: "Outreach BDR", score: 83 },
  { name: "Alex R.", company: "ZoomInfo Rep", score: 79 },
  { name: "Sam L.", company: "Seismic AE", score: 74 },
  { name: "Taylor B.", company: "Salesloft SDR", score: 68 },
];

// ─── Daily-seeded leaderboard rotation ───────────────────────────────────────
// Declared here so both SEED_USERS and SIQ_FAKE_LB are already defined above.
function getDayOfYear() {
  return Math.floor((Date.now() - new Date(new Date().getFullYear(), 0, 0)) / 86400000);
}
function seededShuffle(arr, seed) {
  const a = [...arr];
  let s = seed;
  for (let i = a.length - 1; i > 0; i--) {
    s = (s * 1664525 + 1013904223) & 0xffffffff;
    const j = Math.abs(s) % (i + 1);
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}
const SEED_USERS_DAILY = [
  ...SEED_USERS.slice(0, 3),
  ...seededShuffle(SEED_USERS.slice(3), getDayOfYear()),
];
const SIQ_FAKE_LB_DAILY = [
  ...SIQ_FAKE_LB.slice(0, 1),
  ...seededShuffle(SIQ_FAKE_LB.slice(1), getDayOfYear() + 7),
];

async function siqCallClaude(userMsg, systemMsg) {
  const sys = systemMsg || "You are SalesLab AI. You must respond with ONLY a raw JSON object. Do not include any text before or after the JSON. Do not use markdown code fences. Start your response with { and end with }.";
  const res = await fetch("https://nahextkqnsmluuskjxps.supabase.co/functions/v1/anthropic-proxy", {
    method: "POST",
    headers: { "Content-Type": "application/json", "Authorization": `Bearer ${SUPABASE_ANON_KEY}` },
    body: JSON.stringify({ max_tokens: 1000, system: sys, messages: [{ role: "user", content: userMsg }] }),
  });
  const data = await res.json();
  console.log("[SIQ DEBUG] status:", res.status, "keys:", Object.keys(data));
  // Extract text from every possible proxy response shape
  let text = "";
  if (Array.isArray(data.content)) {
    text = data.content.filter(b => b.type === "text").map(b => b.text).join("") ||
           data.content.map(b => b.text || b.content || "").join("");
  } else if (data.content && typeof data.content === "string") {
    text = data.content;
  } else if (data.choices) {
    text = data.choices[0]?.message?.content || data.choices[0]?.text || "";
  } else if (data.text) {
    text = data.text;
  } else if (data.completion) {
    text = data.completion;
  } else if (data.response) {
    text = typeof data.response === "string" ? data.response : JSON.stringify(data.response);
  }
  console.log("[SIQ DEBUG] text (first 300):", text.slice(0, 300));
  if (!text) throw new Error("Empty response from proxy. Keys: " + Object.keys(data).join(","));
  // Find JSON - look for first { and last }
  const s = text.indexOf("{");
  const e = text.lastIndexOf("}");
  if (s === -1 || e === -1 || e <= s) throw new Error("No JSON object found in: " + text.slice(0, 100));
  const jsonStr = text.slice(s, e + 1);
  try {
    return JSON.parse(jsonStr);
  } catch(parseErr) {
    console.error("[SIQ DEBUG] Parse failed on:", jsonStr.slice(0, 200));
    throw new Error("JSON parse failed: " + parseErr.message);
  }
}


// ── SIQ localStorage helpers ────────────────────────────────────────────────
function siqGetHistory() {
  try { return JSON.parse(localStorage.getItem("siq_history") || "[]"); } catch(e) { return []; }
}
function siqSaveAttempt(roleId, industryId, score, skills, tier) {
  try {
    const history = siqGetHistory();
    const today = new Date().toISOString().split("T")[0];
    history.unshift({ date: today, roleId, industryId, score, skills, tier, ts: Date.now() });
    localStorage.setItem("siq_history", JSON.stringify(history.slice(0, 30)));
  } catch(e) {}
}
function siqGetStreak() {
  try {
    const history = siqGetHistory();
    if (!history.length) return 0;
    const today = new Date().toISOString().split("T")[0];
    const dates = [...new Set(history.map(h => h.date))].sort().reverse();
    let streak = 0;
    let expected = today;
    for (const d of dates) {
      if (d === expected) {
        streak++;
        const dt = new Date(expected);
        dt.setDate(dt.getDate() - 1);
        expected = dt.toISOString().split("T")[0];
      } else break;
    }
    return streak;
  } catch(e) { return 0; }
}
function siqGetAttemptCount(roleId) {
  try {
    const history = siqGetHistory();
    return history.filter(h => h.roleId === roleId).length;
  } catch(e) { return 0; }
}
function siqGetTodayScore(roleId) {
  try {
    const history = siqGetHistory();
    const today = new Date().toISOString().split("T")[0];
    return history.find(h => h.roleId === roleId && h.date === today) || null;
  } catch(e) { return null; }
}
function siqGetWeakSkills(roleId) {
  try {
    const history = siqGetHistory().filter(h => h.roleId === roleId).slice(0, 5);
    if (!history.length) return [];
    const totals = {};
    const counts = {};
    history.forEach(h => {
      if (h.skills) Object.entries(h.skills).forEach(([k,v]) => {
        totals[k] = (totals[k] || 0) + v;
        counts[k] = (counts[k] || 0) + 1;
      });
    });
    return Object.entries(totals)
      .map(([k,v]) => ({ name: k, avg: Math.round(v / counts[k]) }))
      .sort((a,b) => a.avg - b.avg)
      .slice(0, 2)
      .map(s => s.name);
  } catch(e) { return []; }
}

async function siqSaveEmailToSupabase(email, score, tier, roleId, industryId) {
  try {
    await fetch(`${SUPABASE_URL}/rest/v1/siq_leads`, {
      method: "POST",
      headers: {
        "apikey": SUPABASE_ANON_KEY,
        "Authorization": `Bearer ${SUPABASE_ANON_KEY}`,
        "Content-Type": "application/json",
        "Prefer": "resolution=merge-duplicates",
      },
      body: JSON.stringify({
        email: email.trim().toLowerCase(),
        score, tier,
        role_id: roleId,
        industry_id: industryId,
        created_at: new Date().toISOString(),
      }),
    });
  } catch(e) { console.log("[SIQ] Email save failed silently:", e.message); }
}

function SalesIQAssessment({ onExit, isPro, currentUser }) {
  const [screen, setScreen] = useState("role");
  const [siqIndustry, setSiqIndustry] = useState(null);
  const [siqRole, setSiqRole] = useState(null);
  const [siqStep, setSiqStep] = useState(1);
  const [questions, setQuestions] = useState([]);
  const [currentQ, setCurrentQ] = useState(0);
  const [userAnswers, setUserAnswers] = useState([]);
  const [scoreData, setScoreData] = useState(null);
  const [loadingMsg, setLoadingMsg] = useState("Building your scenarios...");
  const [toastMsg, setToastMsg] = useState("");
  const [challengeSlug, setChallengeSlug] = useState("");
  const [emailCapture, setEmailCapture] = useState("");
  const [emailSubmitted, setEmailSubmitted] = useState(false);
  const [emailError, setEmailError] = useState("");
  const [showEmailGate, setShowEmailGate] = useState(false);
  const [pendingScoreData, setPendingScoreData] = useState(null);
  const [isChallenged, setIsChallenged] = useState(false);
  const [challengerScore, setChallengerScore] = useState(null);
  const [showFreeUpgrade, setShowFreeUpgrade] = useState(false);
  const step2Ref = useRef(null);
  const step3Ref = useRef(null);

  const streakDays = siqGetStreak() || 1;
  const attemptCount = siqRole ? siqGetAttemptCount(siqRole.id) : 0;
  const weakSkills = siqRole ? siqGetWeakSkills(siqRole.id) : [];

  // Check if user arrived via challenge link
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const iqParam = params.get("iq");
    if (iqParam) {
      const parts = iqParam.split("-");
      if (parts.length >= 2) {
        setChallengerScore(parts[parts.length - 1]);
        setIsChallenged(true);
      }
    }
  }, []);

  function showToast(msg) {
    setToastMsg(msg);
    setTimeout(() => setToastMsg(""), 2500);
  }

  function pickIndustry(ind) {
    setSiqIndustry(ind);
    setSiqRole(null);
    setSiqStep(2);
    setTimeout(() => step2Ref.current && step2Ref.current.scrollIntoView({ behavior: "smooth", block: "start" }), 120);
  }

  function pickRole(r) {
    setSiqRole(r);
    setSiqStep(3);
    setTimeout(() => step3Ref.current && step3Ref.current.scrollIntoView({ behavior: "smooth", block: "start" }), 120);
  }

  function resetRole() {
    setSiqIndustry(null); setSiqRole(null); setSiqStep(1);
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  function buildQuestionPrompt() {
    // Cross-attempt difficulty (how hard the overall session is)
    const sessionDiff = attemptCount >= 5 ? "expert" : attemptCount >= 3 ? "advanced" : attemptCount >= 1 ? "intermediate" : "foundational";

    const weakFocus = weakSkills.length > 0 && attemptCount >= 3
      ? `Incorporate the rep's documented weak areas (${weakSkills.join(", ")}) into at least 2 questions.`
      : "";

    // Per-question difficulty tiers — always ramp within the session regardless of attempt count
    const qDifficulty = [
      { tier: "warm-up",    label: "Q1 (warm-up)",    inst: "A realistic scenario where a rep with 6 months experience could identify the best answer through solid reasoning. Wrong answers are plausible rookie mistakes." },
      { tier: "moderate",   label: "Q2 (moderate)",   inst: "Increase the pressure. The scenario has competing priorities. Wrong answers represent things reps with 1-2 years of experience commonly do wrong." },
      { tier: "challenging",label: "Q3 (challenging)", inst: "High pressure. No obviously correct answer on first read. Wrong answers each represent a legitimate tactic that experienced reps use — but fail here. Requires real pattern recognition." },
      { tier: "hard",       label: "Q4 (hard)",        inst: "The scenario involves subtle buyer psychology or a nuanced multi-step situation. All 4 answers should look reasonable. Only a rep who truly understands buyer dynamics picks the best one." },
      { tier: "elite",      label: "Q5 (elite)",       inst: "Elite difficulty. Multi-layered scenario with competing signals. Wrong answers should each represent what a good rep would do in a slightly different context — the correct answer requires understanding WHY this specific situation demands a different approach. A rep who has closed 100+ deals and still thinks hard about this question is the target." },
    ];

    // Randomize category order so questions never arrive in the same sequence
    const categories = shuffleArray(["Discovery", "Objection Handling", "Closing Ability", "Prospecting Instinct", "Negotiation Awareness"]);

    // Session-level context (used for extra pressure on advanced/expert attempts)
    const sessionContext = sessionDiff === "expert"
      ? "This is an EXPERT-level session. The rep has taken this test multiple times. Every scenario must be genuinely difficult — no easy eliminations, no obvious correct answer. Think top 5% of reps."
      : sessionDiff === "advanced"
      ? "This is an ADVANCED session. The rep has real experience. Scenarios should involve real-world complexity and require non-obvious answers."
      : "";

    return `Generate 5 sales scenario questions for a ${siqRole.name} in ${siqIndustry.name}.
${sessionContext}
${weakFocus}

ANTI-GENERIC RULE — CRITICAL:
Every scenario must be so specific to ${siqRole.name} in ${siqIndustry.name} that it could NOT appear in a test for any other role or industry. Use real industry vocabulary, actual buyer archetypes, realistic dollar amounts, and situations unique to this vertical.

BANNED GENERIC PATTERNS (never write anything like these):
- "A decision-maker says they need to think it over"
- "A prospect says your price is too high" (without specific context)
- "You're on a first call and they seem guarded"
- Any scenario that starts with "You're on a call with a decision-maker"

INSTEAD write scenarios like these (for illustration only — generate fresh unique ones):
- Solar Consultant: "A homeowner in Phoenix just got a $340 utility bill and is interested, but their spouse wasn't home during your site visit and now they're saying they need to wait..."
- SaaS AE: "Your champion at a 200-person logistics company went dark 3 days before the legal review was supposed to start. Your last two emails went unanswered..."
- Roofing Rep: "The homeowner shows you a competitor's itemized quote that's $2,400 less. The competitor used 3-tab shingles; you quoted architectural. The homeowner doesn't know the difference..."

CRITICAL RULES FOR WRONG ANSWERS:
- Every wrong answer must be something a real, experienced rep might actually do in a moment of weakness
- Wrong answers that are obviously bad will be rejected
- Ask yourself: "Would a rep with 2+ years of experience plausibly choose this under pressure?" If not, rewrite it
- The correct answer must require knowing specifically WHY the other answers fail in this context

QUESTION STRUCTURE — one question per category in this exact order:
${categories.map((cat, i) => `Q${i+1} category: "${cat}" — Difficulty: ${qDifficulty[i].label}`).join("\n")}

Per-question difficulty:
${qDifficulty.map((q, i) => `Q${i+1} (${categories[i]}): ${q.inst}`).join("\n")}

SCENARIO REQUIREMENTS:
- 2-3 sentences with specific dollar amounts, company sizes, timelines, or buyer details
- Explanations must name the tactic AND explain why the most tempting wrong answer fails
- Question: "What do you do?" or a specific situational variant — never theoretical

Return ONLY a raw JSON object. No markdown. No preamble. Start with { end with }.
{"questions":[{"id":1,"category":"${categories[0]}","difficulty":"${qDifficulty[0].tier}","scenario":"...","question":"...","options":[{"letter":"A","text":"..."},{"letter":"B","text":"..."},{"letter":"C","text":"..."},{"letter":"D","text":"..."}],"correct":"B","explanation":"Why B works AND why the most tempting wrong answer fails."}]}`;
  }

  async function startAssessment() {
    // Free user daily gate — 1 attempt per day
    if (!isPro) {
      const today = new Date().toISOString().split("T")[0];
      const history = siqGetHistory();
      const playedToday = history.some(h => h.date === today);
      if (playedToday) {
        setShowFreeUpgrade(true);
        return;
      }
    }
    setLoadingMsg(`Building your ${attemptCount >= 3 ? "advanced" : "personalized"} scenarios...`);
    setScreen("loading");
    const prompt = buildQuestionPrompt();
    try {
      const data = await siqCallClaude(prompt);
      if (!data.questions || !Array.isArray(data.questions) || data.questions.length < 3) {
        throw new Error("Invalid questions structure");
      }
      // Shuffle answer options per question so correct answer position is unpredictable
      // Re-label letters A→D in new order, update correct pointer to match
      const shuffled = data.questions.map(q => {
        const shuffledOpts = shuffleArray(q.options);
        const relabeled = shuffledOpts.map((opt, i) => ({ ...opt, originalLetter: opt.letter, letter: ["A","B","C","D"][i] }));
        const newCorrect = relabeled.find(o => o.originalLetter === q.correct)?.letter || q.correct;
        return { ...q, options: relabeled, correct: newCorrect };
      });
      setQuestions(shuffled);
      setCurrentQ(0); setUserAnswers([]);
      setScreen("test");
    } catch(e) {
      console.error("[SIQ] startAssessment failed:", e.message);
      const indName = siqIndustry ? siqIndustry.name : "your industry";
      const fallbackQ = [
        { id:1, category:"Discovery", scenario:"You're on a first call with a " + indName + " decision-maker. They agreed to the meeting but are guarded. You have 10 minutes before they have another call.", question:"What's your highest-leverage opening question?", options:[{letter:"A",text:"Can I tell you what makes us different from other " + indName + " solutions?"},{letter:"B",text:"What made you agree to this call today?"},{letter:"C",text:"How many other vendors are you evaluating?"},{letter:"D",text:"What's your timeline for making a decision?"}], correct:"B", explanation:"Asking what made them take the meeting reveals their real pain and gives you the exact hook to build the entire conversation around." },
        { id:2, category:"Objection Handling", scenario:"You've delivered a strong presentation. The decision-maker says: 'This looks great but I need to run it by my partner first.' You suspect this is a stall, not a real objection.", question:"What do you do?", options:[{letter:"A",text:"Say 'of course' and schedule a follow-up for next week"},{letter:"B",text:"Ask 'If your partner is on board, is there anything on your end that would prevent moving forward?'"},{letter:"C",text:"Offer a discount to close before they talk to their partner"},{letter:"D",text:"Ask for the partner's contact info so you can present directly to them"}], correct:"B", explanation:"Isolating the prospect's own objection first reveals whether the partner is real resistance or a convenient escape — and creates commitment before you involve anyone else." },
        { id:3, category:"Closing Ability", scenario:"You've been working a deal for 3 weeks. The prospect is clearly interested but keeps pushing the timeline. Today they said: 'We'll definitely move forward — just not this month.'", question:"What's your move?", options:[{letter:"A",text:"Send a calendar invite for next month and wait"},{letter:"B",text:"Ask what specifically needs to happen this month before they're ready"},{letter:"C",text:"Tell them you have a promotion ending this Friday"},{letter:"D",text:"Ask: 'Help me understand — what changes next month that makes it the right time?'"}], correct:"D", explanation:"Asking what changes next month forces them to articulate the real reason — most of the time there isn't one, and the prospect realizes it mid-sentence, creating self-generated urgency." },
        { id:4, category:"Prospecting Instinct", scenario:"You get a referral from an existing client. The referral says they're 'interested' but doesn't respond to your first two emails.", question:"What's your approach?", options:[{letter:"A",text:"Send a third email with more information about your product"},{letter:"B",text:"Call and leave a voicemail referencing the mutual client"},{letter:"C",text:"Ask your mutual client to re-introduce you with context about why it's relevant for them right now"},{letter:"D",text:"Wait two weeks and try again"}], correct:"C", explanation:"A warm re-introduction from the mutual connection carries exponentially more trust than any cold follow-up — the referral source is your best asset, use them." },
        { id:5, category:"Negotiation Awareness", scenario:"You're on the 1-yard line. The buyer says: 'We want to move forward but need you to throw in free implementation — otherwise we'll go with the competitor.'", question:"What do you do?", options:[{letter:"A",text:"Agree to free implementation to close the deal"},{letter:"B",text:"Say implementation isn't negotiable and hold firm"},{letter:"C",text:"Ask: 'If we can find a creative way to handle implementation costs, what else needs to be true to sign this week?'"},{letter:"D",text:"Counter with a 10% discount instead of free implementation"}], correct:"C", explanation:"Never give a concession without extracting a commitment in return. This move makes them confirm there are no other blockers while making them feel heard — setting up a mutual close." },
      ]
      // Shuffle fallback questions and relabel options A→D sequentially
      const shuffledFallback = shuffleArray(fallbackQ).map(q => {
        const shuffledOpts = shuffleArray(q.options);
        const relabeled = shuffledOpts.map((opt, i) => ({ ...opt, originalLetter: opt.letter, letter: ["A","B","C","D"][i] }));
        const newCorrect = relabeled.find(o => o.originalLetter === q.correct)?.letter || q.correct;
        return { ...q, options: relabeled, correct: newCorrect };
      });
      setQuestions(shuffledFallback);
      setCurrentQ(0); setUserAnswers([]);
      setScreen("test");
    }
  }

  function handleAnswer(letter, q) {
    const isCorrect = letter === q.correct;
    setUserAnswers(prev => [...prev, { category: q.category, chosen: letter, correct: q.correct, isCorrect }]);
  }

  function handleSkip() {
    const q = questions[currentQ];
    const newAnswers = [...userAnswers, { category: q.category, chosen: null, correct: q.correct, isCorrect: false }];
    setUserAnswers(newAnswers);
    if (currentQ >= 4) handleScoring(newAnswers);
    else setCurrentQ(n => n + 1);
  }

  function handleNext() {
    if (currentQ >= 4) handleScoring(userAnswers);
    else setCurrentQ(n => n + 1);
  }

  async function handleScoring(answers) {
    setLoadingMsg("Calculating your Sales IQ...");
    setScreen("scoring");
    const numCorrect = answers.filter(a => a.isCorrect).length;
    const summary = answers.map(a => ({ category: a.category, correct: a.isCorrect }));
    const prompt = `Score this Sales IQ assessment for a ${siqRole.name} in ${siqIndustry.name}. Results: ${JSON.stringify(summary)}. Correct: ${numCorrect}/5.
Score ranges: 5=90-100, 4=75-89, 3=60-74, 2=40-59, 0-1=0-39. Add realistic variance within range based on which categories they got right.
Tiers: 90-100=Elite Sales Mind, 75-89=Strong Sales Skills, 60-74=Developing Sales Skills, 40-59=Needs Sales Training, 0-39=Beginner Level.
Return raw JSON starting with { ending with }:
{"score":82,"tier":"Strong Sales Skills","rank_pct":"Top 25%","rank_num":3,"skills":{"Discovery":85,"Objection Handling":70,"Closing Ability":90,"Prospecting Instinct":58,"Negotiation Awareness":71},"strength":"Closing Ability","weakness":"Prospecting Instinct","tip":"One specific, actionable coaching tip based on their weakest category."}`;
    let scoreResult;
    try {
      scoreResult = await siqCallClaude(prompt);
    } catch(e) {
      const tiers = ["Beginner Level","Needs Sales Training","Developing Sales Skills","Strong Sales Skills","Elite Sales Mind"];
      const bases = [20,50,67,82,95];
      scoreResult = { score: Math.max(0,Math.min(100, bases[numCorrect]+Math.floor(Math.random()*6)-3)), tier: tiers[numCorrect], rank_pct: numCorrect>=4?"Top 10%":numCorrect>=3?"Top 25%":"Top 50%", rank_num: numCorrect>=4?2:numCorrect>=3?4:6, skills:{Discovery:70,"Objection Handling":65,"Closing Ability":75,"Prospecting Instinct":60,"Negotiation Awareness":70}, strength:"Closing Ability", weakness:"Prospecting Instinct", tip:"Focus on asking one more discovery question before pitching your solution." };
    }
    // Save to localStorage
    siqSaveAttempt(siqRole.id, siqIndustry.id, scoreResult.score, scoreResult.skills, scoreResult.tier);
    // Save to Supabase if logged in
    if (currentUser?.email) {
      siqSaveEmailToSupabase(currentUser.email, scoreResult.score, scoreResult.tier, siqRole.id, siqIndustry.id);
      setEmailSubmitted(true);
    }
    const slug = scoreResult.score; // numeric score used as the challenge param
    setChallengeSlug(slug);
    setPendingScoreData(scoreResult);
    // Show email gate for non-logged-in users who haven't submitted email
    if (!currentUser && !emailSubmitted) {
      setShowEmailGate(true);
      setScreen("results");
    } else {
      setScoreData(scoreResult);
      setScreen("results");
    }
  }

  async function handleEmailSubmit() {
    if (!emailCapture.includes("@")) { setEmailError("Please enter a valid email."); return; }
    setEmailError("");
    await siqSaveEmailToSupabase(emailCapture, pendingScoreData.score, pendingScoreData.tier, siqRole.id, siqIndustry.id);
    setEmailSubmitted(true);
    setShowEmailGate(false);
    setScoreData(pendingScoreData);
  }

  function copyText(text, msg) {
    // Robust clipboard: try modern API first, fall back to execCommand for iOS/HTTP
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(text).then(() => showToast(msg)).catch(() => {
        _copyFallback(text, msg);
      });
    } else {
      _copyFallback(text, msg);
    }
  }
  function _copyFallback(text, msg) {
    try {
      const ta = document.createElement("textarea");
      ta.value = text;
      ta.style.cssText = "position:fixed;top:-9999px;left:-9999px;opacity:0;";
      document.body.appendChild(ta);
      ta.focus(); ta.select();
      document.execCommand("copy");
      document.body.removeChild(ta);
      showToast(msg);
    } catch { showToast("Long-press to copy: " + text.slice(0, 40) + "…"); }
  }

  const sW = { fontFamily: "'Inter', sans-serif" };
  // Stable full-screen style — dvh adjusts for mobile toolbars, overscroll prevents rubber-banding shift
  const fixedScreen = {
    position: "fixed", inset: 0, zIndex: 100,
    background: "#E8EDF5",
    overflowY: "auto",
    overscrollBehavior: "contain",
    fontFamily: "'Inter', sans-serif",
    // Prevent layout shift on orientation change
    minHeight: "-webkit-fill-available",
  };
  const challengeUrl = `https://thesaleslabai.com/challenge`;
  const challengeDisplayUrl = challengeSlug
    ? `https://thesaleslabai.com/challenge?s=${challengeSlug}&r=${encodeURIComponent(siqRole?.name||"Rep")}&i=${encodeURIComponent(siqIndustry?.name||"")}`
    : `https://thesaleslabai.com/challenge`;

  // ── Challenge banner (shown if arrived via challenge link) ──
  const ChallengeBanner = () => isChallenged ? (
    <div style={{ background:"#EFF6FF", border:"0.5px solid #BFDBFE", borderRadius:10, padding:"12px 18px", marginBottom:20, display:"flex", alignItems:"center", gap:12 }}>
      <div style={{ fontSize:20 }}>⚡</div>
      <div>
        <div style={{ fontSize:13, fontWeight:600, color:"#1E3A8A" }}>You've been challenged!</div>
        <div style={{ fontSize:12, color:"#1D4ED8" }}>Someone scored {challengerScore} on the Sales IQ. Take the test and see if you can beat it.</div>
      </div>
    </div>
  ) : null;

  // ── Role Select Screen ──
  if (screen==="role") return (
    <div style={{ ...fixedScreen }}>
      <style>{`
        .siq-role-wrap { max-width:680px; margin:0 auto; padding:28px 16px 60px; }
        .siq-industry-grid { display:grid; grid-template-columns:repeat(3,1fr); gap:10px; }
        .siq-role-grid { display:grid; grid-template-columns:repeat(3,1fr); }
        @media (max-width:500px) {
          .siq-role-wrap { padding:20px 12px 60px; }
          .siq-industry-grid { grid-template-columns:repeat(2,1fr); }
          .siq-role-grid { grid-template-columns:repeat(2,1fr); }
        }
      `}</style>
      <div style={{ background:"#fff", borderBottom:"0.5px solid #D1D9E6", paddingTop:"max(10px, env(safe-area-inset-top))", paddingLeft:24, paddingRight:24, paddingBottom:12, display:"flex", alignItems:"center", justifyContent:"space-between", position:"sticky", top:0, zIndex:10 }}>
        <div style={{ display:"flex", alignItems:"center", gap:10 }}>
          <div style={{ width:32, height:32, background:"#1a2744", borderRadius:7, display:"flex", alignItems:"center", justifyContent:"center", fontSize:11, color:"#fff", fontWeight:700 }}>SL</div>
          <div><div style={{ fontSize:13, fontWeight:700, color:"#0F172A", letterSpacing:"0.02em" }}>SALESLAB AI</div><div style={{ fontSize:10, color:"#94A3B8", letterSpacing:"0.08em" }}>TRAIN · TEST · CLOSE</div></div>
        </div>
        <button onClick={onExit} style={{ fontSize:12, color:"#64748B", background:"#F8FAFC", border:"0.5px solid #D1D9E6", borderRadius:7, padding:"5px 12px", cursor:"pointer" }}>← Back to Dashboard</button>
      </div>
      <div className="siq-role-wrap">
        <ChallengeBanner />
        <div style={{ fontSize:10, fontWeight:600, letterSpacing:"0.1em", color:"#94A3B8", textTransform:"uppercase", marginBottom:8 }}>Sales IQ Assessment</div>
        <div style={{ fontSize:26, fontWeight:700, color:"#0F172A", letterSpacing:"-0.5px", marginBottom:6 }}>Tell us about yourself</div>
        <div style={{ fontSize:14, color:"#64748B", lineHeight:1.6, marginBottom:28 }}>We'll tailor your 5 scenarios to your industry and role so every question feels real. Takes about 3 minutes.</div>
        <div style={{ display:"flex", alignItems:"center", gap:8, marginBottom:24 }}>
          {[["1","Pick your industry"],["2","Pick your role"],["3","Start the test"]].map(([n,label],i)=>{
            const st=i+1; const bg=siqStep>st?"#DBEAFE":siqStep===st?"#1D4ED8":"#F1F5F9"; const co=siqStep>st?"#1D4ED8":siqStep===st?"#fff":"#94A3B8"; const lc=siqStep>=st?"#0F172A":"#94A3B8";
            return (<React.Fragment key={n}>{i>0&&<div style={{ flex:1, height:1, background:"#E2E8F0" }}/>}<div style={{ display:"flex", alignItems:"center", gap:6 }}><div style={{ width:22, height:22, borderRadius:6, background:bg, color:co, display:"flex", alignItems:"center", justifyContent:"center", fontSize:11, fontWeight:700 }}>{n}</div><div style={{ fontSize:12, fontWeight:500, color:lc }}>{label}</div></div></React.Fragment>);
          })}
        </div>
        <div style={{ marginBottom:28 }}>
          <div style={{ fontSize:11, fontWeight:600, letterSpacing:"0.07em", textTransform:"uppercase", color:"#94A3B8", marginBottom:12 }}>Step 1 · Select your industry</div>
          <div className="siq-industry-grid">
            {SIQ_INDUSTRIES.map(ind=>(
              <div key={ind.id} onClick={()=>pickIndustry(ind)} style={{ background:siqIndustry?.id===ind.id?"#EFF6FF":"#fff", border:`0.5px solid ${siqIndustry?.id===ind.id?"#1D4ED8":"#D1D9E6"}`, borderRadius:10, padding:"14px 12px", cursor:"pointer", display:"flex", flexDirection:"column", alignItems:"center", textAlign:"center", gap:6 }}>
                <div style={{ fontSize:22 }}>{ind.icon}</div>
                <div style={{ fontSize:13, fontWeight:600, color:siqIndustry?.id===ind.id?"#1D4ED8":"#0F172A", lineHeight:1.3 }}>{ind.name}</div>
                <div style={{ fontSize:11, color:"#94A3B8", lineHeight:1.3 }}>{ind.desc}</div>
              </div>
            ))}
          </div>
        </div>
        {siqStep>=2&&siqIndustry&&(
          <div ref={step2Ref} style={{ marginBottom:24 }}>
            <div style={{ fontSize:11, fontWeight:600, letterSpacing:"0.07em", textTransform:"uppercase", color:"#94A3B8", marginBottom:12 }}>Step 2 · Select your role</div>
            <div style={{ background:"#fff", border:"0.5px solid #D1D9E6", borderRadius:12, overflow:"hidden" }}>
              <div style={{ padding:"14px 18px", borderBottom:"0.5px solid #F1F5F9", display:"flex", alignItems:"center", gap:10 }}>
                <div style={{ fontSize:18 }}>{siqIndustry.icon}</div>
                <div style={{ fontSize:14, fontWeight:600, color:"#0F172A" }}>{siqIndustry.name}</div>
                <div style={{ fontSize:12, color:"#94A3B8", marginLeft:"auto" }}>{siqIndustry.roles.length+1} roles</div>
              </div>
              <div className="siq-role-grid">
                {[...siqIndustry.roles, SIQ_OTHER_ROLE].map((r,i)=>(
                  <div key={r.id} onClick={()=>pickRole(r)} style={{ padding:"14px 16px", borderRight:(i+1)%3===0?"none":"0.5px solid #F1F5F9", borderTop:"0.5px solid #F1F5F9", cursor:"pointer", background:siqRole?.id===r.id?"#EFF6FF":r.isOther?"#F8FAFC":"#fff" }}>
                    <div style={{ fontSize:13, fontWeight:600, color:siqRole?.id===r.id?"#1D4ED8":r.isOther?"#64748B":"#0F172A", marginBottom:2 }}>{r.isOther?"✳️ ":""}{r.name}</div>
                    <div style={{ fontSize:11, color:"#94A3B8", lineHeight:1.4 }}>{r.desc}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
        {siqStep>=3&&siqRole&&(
          <div ref={step3Ref}>
            <div style={{ background:"#EFF6FF", border:"0.5px solid #BFDBFE", borderRadius:10, padding:"12px 16px", marginBottom:20, display:"flex", alignItems:"center", justifyContent:"space-between" }}>
              <div style={{ fontSize:13, color:"#1E3A8A" }}>You selected: <strong>{siqIndustry.name}</strong> · <strong>{siqRole.name}</strong></div>
              <div onClick={resetRole} style={{ fontSize:12, color:"#1D4ED8", cursor:"pointer", fontWeight:500 }}>Change →</div>
            </div>
            <button onClick={startAssessment} style={{ width:"100%", background:"#1D4ED8", color:"#fff", border:"none", borderRadius:10, padding:14, fontSize:15, fontWeight:600, cursor:"pointer" }}>
              {attemptCount>=3?`Start attempt #${attemptCount+1} — harder questions →`:"Start my Sales IQ test →"}
            </button>
            {attemptCount>=1&&(
              <div style={{ background:"#EFF6FF", border:"0.5px solid #BFDBFE", borderRadius:8, padding:"8px 14px", marginTop:10 }}>
                <div style={{ fontSize:11, color:"#1D4ED8" }}>
                  {attemptCount>=3?`⚡ Attempt #${attemptCount+1} — targeting your weak spots: ${weakSkills.join(" & ")||"all categories"}`:attemptCount>=1?`Attempt #${attemptCount+1} — questions getting harder based on your history`:""}
                </div>
              </div>
            )}
            <div style={{ textAlign:"center", marginTop:10, fontSize:12, color:"#94A3B8" }}>Free · 5 questions · {streakDays>1?`🔥 ${streakDays}-day streak`:"Start your streak today"}</div>
          </div>
        )}
      </div>
      {toastMsg&&<div style={{ position:"fixed", bottom:24, left:"50%", transform:"translateX(-50%)", background:"#1D4ED8", color:"#fff", fontSize:13, fontWeight:500, padding:"10px 20px", borderRadius:8, zIndex:200, whiteSpace:"nowrap" }}>{toastMsg}</div>}
    </div>
  );

  // ── Loading / Scoring Screen ──
  if (screen==="loading"||screen==="scoring") return (
    <div style={{ ...fixedScreen, display:"flex", alignItems:"center", justifyContent:"center", flexDirection:"column", gap:20 }}>
      <style>{`@keyframes siq-spin{to{transform:rotate(360deg)}}`}</style>
      <div style={{ width:36, height:36, border:"2.5px solid #E2E8F0", borderTopColor:"#1D4ED8", borderRadius:"50%", animation:"siq-spin 0.8s linear infinite" }}/>
      <div style={{ fontSize:16, fontWeight:600, color:"#0F172A" }}>{loadingMsg}</div>
      <div style={{ fontSize:13, color:"#94A3B8" }}>Tailored for {siqIndustry?.name} · {siqRole?.name}</div>
    </div>
  );

  // ── Email Gate Screen (overlays results) ──
  if (screen==="results"&&showEmailGate) return (
    <div style={{ ...fixedScreen, display:"flex", alignItems:"center", justifyContent:"center" }}>
      <div style={{ background:"#fff", border:"0.5px solid #D1D9E6", borderRadius:16, padding:"32px 28px", maxWidth:440, width:"100%", margin:"0 24px" }}>
        <div style={{ fontSize:36, marginBottom:12, textAlign:"center" }}>🎯</div>
        <div style={{ fontSize:20, fontWeight:700, color:"#0F172A", textAlign:"center", marginBottom:8, letterSpacing:"-0.3px" }}>Your result is in!</div>
        <div style={{ fontSize:13, color:"#64748B", textAlign:"center", marginBottom:24, lineHeight:1.6 }}>Enter your email to see your Sales IQ Score, skill breakdown, and share your result. Free forever — no spam.</div>
        <input
          value={emailCapture}
          onChange={e=>setEmailCapture(e.target.value)}
          onKeyDown={e=>e.key==="Enter"&&handleEmailSubmit()}
          placeholder="your@email.com"
          style={{ width:"100%", padding:"11px 14px", borderRadius:8, border:`1px solid ${emailError?"#FCA5A5":"#E2E8F0"}`, background:"#F8FAFC", fontSize:14, color:"#0F172A", marginBottom:8, outline:"none", fontFamily:"'Inter', sans-serif" }}
        />
        {emailError&&<div style={{ fontSize:12, color:"#DC2626", marginBottom:8 }}>{emailError}</div>}
        <button onClick={handleEmailSubmit} style={{ width:"100%", background:"#1D4ED8", color:"#fff", border:"none", borderRadius:10, padding:"13px", fontSize:15, fontWeight:600, cursor:"pointer", marginBottom:12 }}>See my Sales IQ Score →</button>
        <div style={{ textAlign:"center", fontSize:11, color:"#94A3B8" }}>No credit card · No spam · Unsubscribe anytime</div>
      </div>
    </div>
  );

// ── Test Screen ──
  if (screen==="test"&&questions.length>0) {
    const q=questions[currentQ];
    const answered=userAnswers.length>currentQ;
    const lastAnswer=answered?userAnswers[currentQ]:null;
    const correctSoFar=userAnswers.filter(a=>a.isCorrect).length;
    return (
      <div style={{ ...fixedScreen }}>
        <style>{`
          .siq-question-wrap { max-width:820px; margin:0 auto; padding:20px 16px; }
          .siq-question-body { display:flex; gap:20px; align-items:flex-start; }
          .siq-question-main { flex:1; min-width:0; }
          .siq-question-sidebar { width:180px; flex-shrink:0; }
          @media (max-width:600px) {
            .siq-question-wrap { padding:14px 12px; }
            .siq-question-body { flex-direction:column; }
            .siq-question-sidebar { width:100%; display:flex; gap:10px; }
            .siq-question-sidebar > div { flex:1; }
          }
        `}</style>
        <div style={{ background:"#fff", borderBottom:"0.5px solid #D1D9E6", paddingTop:"max(10px, env(safe-area-inset-top))", paddingLeft:24, paddingRight:24, paddingBottom:12, display:"flex", alignItems:"center", justifyContent:"space-between", position:"sticky", top:0, zIndex:10 }}>
          <div style={{ display:"flex", alignItems:"center", gap:10 }}>
            <div style={{ width:32, height:32, background:"#1a2744", borderRadius:7, display:"flex", alignItems:"center", justifyContent:"center", fontSize:11, color:"#fff", fontWeight:700 }}>SL</div>
            <div><div style={{ fontSize:13, fontWeight:700, color:"#0F172A" }}>SALESLAB AI</div><div style={{ fontSize:10, color:"#94A3B8", letterSpacing:"0.08em" }}>TRAIN · TEST · CLOSE</div></div>
          </div>
          <button onClick={onExit} style={{ fontSize:12, color:"#64748B", background:"#F8FAFC", border:"0.5px solid #D1D9E6", borderRadius:7, padding:"5px 12px", cursor:"pointer" }}>← Back to Dashboard</button>
        </div>
        <div className="siq-question-wrap">
          <div className="siq-question-body">
            <div className="siq-question-main">
              <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:8 }}>
                <div style={{ fontSize:12, color:"#64748B", fontWeight:500 }}>Question {currentQ+1} of 5</div>
                <div style={{ background:"#DBEAFE", color:"#1D4ED8", fontSize:11, fontWeight:600, padding:"3px 10px", borderRadius:20 }}>Attempt {attemptCount+1} · {siqRole.name}</div>
              </div>
              <div style={{ display:"flex", gap:5, marginBottom:5 }}>
                {[0,1,2,3,4].map(i=><div key={i} style={{ flex:1, height:4, borderRadius:2, background:i<currentQ?"#1D4ED8":i===currentQ?"#93C5FD":"#E2E8F0", transition:"background 0.3s" }}/>)}
              </div>
              <div style={{ fontSize:11, color:"#94A3B8", marginBottom:16 }}>{currentQ===0?"Answer to begin scoring":`${correctSoFar} correct so far`}</div>
              <div style={{ display:"flex", alignItems:"center", gap:8, marginBottom:12 }}>
                <div style={{ background:"#EFF6FF", color:"#1D4ED8", fontSize:11, fontWeight:600, padding:"4px 12px", borderRadius:20, border:"0.5px solid #BFDBFE" }}>{q.category}</div>
                {attemptCount>=3&&weakSkills.includes(q.category)&&<div style={{ background:"#EFF6FF", color:"#1D4ED8", fontSize:10, fontWeight:600, padding:"3px 8px", borderRadius:10, border:"0.5px solid #BFDBFE" }}>⚡ Weak area</div>}
              </div>
              <div style={{ background:"#fff", border:"0.5px solid #D1D9E6", borderRadius:12, padding:22, marginBottom:14 }}>
                <div style={{ fontSize:10, fontWeight:600, letterSpacing:"0.08em", textTransform:"uppercase", color:"#94A3B8", marginBottom:8 }}>Scenario</div>
                <div style={{ background:"#F8FAFC", borderRadius:"0 8px 8px 0", padding:"13px 15px", marginBottom:16, fontSize:13, color:"#334155", lineHeight:1.65, borderLeft:"3px solid #1D4ED8" }}>{q.scenario}</div>
                <div style={{ fontSize:16, fontWeight:600, color:"#0F172A", lineHeight:1.45, marginBottom:18, letterSpacing:"-0.2px" }}>{q.question}</div>
                <div style={{ display:"flex", flexDirection:"column", gap:9 }}>
                  {q.options.map(opt=>{
                    let bg="#fff",border="0.5px solid #D1D9E6",tc="#334155",lb="#F1F5F9",lc="#64748B";
                    if(answered){
                      if(opt.letter===q.correct){bg="#F0FDF4";border="0.5px solid #86EFAC";lb="#16A34A";lc="#fff";tc="#166534";}
                      else if(opt.letter===lastAnswer?.chosen){bg="#F8FAFC";border="0.5px solid #E2E8F0";tc="#94A3B8";}
                      else{bg="#F8FAFC";border="0.5px solid #E2E8F0";tc="#CBD5E1";}
                    }
                    return(
                      <div key={opt.letter} onClick={()=>!answered&&handleAnswer(opt.letter,q)} style={{ padding:"13px 15px",border,borderRadius:10,cursor:answered?"default":"pointer",display:"flex",alignItems:"flex-start",gap:11,background:bg,transition:"all 0.12s" }}>
                        <div style={{ width:24,height:24,borderRadius:6,background:lb,border:"0.5px solid #E2E8F0",display:"flex",alignItems:"center",justifyContent:"center",fontSize:11,fontWeight:700,color:lc,flexShrink:0,marginTop:1 }}>{opt.letter}</div>
                        <div style={{ fontSize:13,color:tc,lineHeight:1.5 }}>{opt.text}</div>
                      </div>
                    );
                  })}
                </div>
                {answered&&(
                  <div style={{ background:lastAnswer?.isCorrect?"#EFF6FF":"#F8FAFC",border:`0.5px solid ${lastAnswer?.isCorrect?"#BFDBFE":"#E2E8F0"}`,borderRadius:8,padding:"12px 14px",marginTop:14,display:"flex",gap:10 }}>
                    <div style={{ fontSize:15,flexShrink:0 }}>{lastAnswer?.isCorrect?"✓":"→"}</div>
                    <div style={{ fontSize:13,color:lastAnswer?.isCorrect?"#1E3A8A":"#475569",lineHeight:1.55 }}><strong>{lastAnswer?.isCorrect?"Correct. ":"Not quite. "}</strong>{q.explanation}</div>
                  </div>
                )}
              </div>
              <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between" }}>
                {!answered?<button onClick={handleSkip} style={{ fontSize:13,color:"#94A3B8",background:"none",border:"none",cursor:"pointer" }}>Skip</button>:<div/>}
                <button onClick={handleNext} disabled={!answered} style={{ background:answered?"#1D4ED8":"#E2E8F0",color:answered?"#fff":"#94A3B8",border:"none",borderRadius:8,padding:"11px 22px",fontSize:14,fontWeight:600,cursor:answered?"pointer":"default" }}>{currentQ===4?"See my results →":"Next question →"}</button>
              </div>
            </div>
            <div className="siq-question-sidebar">
              <div style={{ background:"#fff",border:"0.5px solid #D1D9E6",borderRadius:10,padding:13,marginBottom:12 }}>
                <div style={{ fontSize:10,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:"#94A3B8",marginBottom:10 }}>Today's leaderboard</div>
                {SIQ_FAKE_LB_DAILY.slice(0,5).map((rep,i)=>(
                  <div key={i} style={{ display:"flex",alignItems:"center",gap:7,padding:"5px 0",borderTop:i===0?"none":"0.5px solid #F1F5F9" }}>
                    <div style={{ width:16,fontSize:13 }}>{i===0?"🥇":i===1?"🥈":i===2?"🥉":i+1}</div>
                    <div style={{ flex:1,fontSize:11,fontWeight:500,color:"#0F172A" }}>{rep.name.split(" ")[0]}</div>
                    <div style={{ fontSize:12,fontWeight:700,color:i===0?"#1D4ED8":"#94A3B8" }}>{rep.score}</div>
                  </div>
                ))}
                <div style={{ display:"flex",alignItems:"center",gap:7,padding:"5px 5px",borderTop:"0.5px solid #F1F5F9",background:"#EFF6FF",borderRadius:5,margin:"2px -5px 0" }}>
                  <div style={{ width:16,fontSize:11,color:"#64748B" }}>?</div>
                  <div style={{ flex:1,fontSize:11,fontWeight:600,color:"#1D4ED8" }}>You</div>
                  <div style={{ fontSize:12,fontWeight:700,color:"#1D4ED8" }}>—</div>
                </div>
              </div>
              <div style={{ background:"#fff",border:"0.5px solid #D1D9E6",borderRadius:10,padding:13 }}>
                <div style={{ fontSize:10,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:"#94A3B8",marginBottom:10 }}>Your streak</div>
                <div style={{ display:"flex",gap:3,marginBottom:5 }}>
                  {[...Array(7)].map((_,i)=><div key={i} style={{ width:16,height:16,borderRadius:3,background:i<Math.min(streakDays,6)?"#1D4ED8":i===Math.min(streakDays,6)?"#93C5FD":"#F1F5F9" }}/>)}
                </div>
                <div style={{ fontSize:11,color:"#94A3B8" }}>{streakDays>1?`${streakDays} days in a row 🔥`:"Day 1 — keep going!"}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ── Results Screen ──
  if (screen==="results"&&scoreData) {
    const s=scoreData;
    const challengePageUrl = `https://thesaleslabai.com/challenge?s=${s.score}&r=${encodeURIComponent(siqRole.name)}&i=${encodeURIComponent(siqIndustry.name)}`;
    const liMsg=`Just scored ${s.score}/100 on the SalesLab AI Sales IQ test — ${s.tier} 🏆

My strongest skill: ${s.strength}. My focus area: ${s.weakness}.

Think you can beat ${s.score}? Take the free daily challenge:
${challengePageUrl}

#SalesIQ #SalesTraining #SalesLab #CloserMindset #SalesPerformance`;
    // LinkedIn share-offsite only supports ?url= — text must be copied separately
    const liShareUrl=`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(challengePageUrl)}`;
    const allReps=[...SIQ_FAKE_LB_DAILY,{name:"You",score:s.score,you:true}].sort((a,b)=>b.score-a.score);
    const history=siqGetHistory().filter(h=>h.roleId===siqRole.id).slice(0,5);
    return (
      <div style={{ ...fixedScreen }}>
        <div style={{ background:"#fff",borderBottom:"0.5px solid #D1D9E6",paddingTop:"max(10px, env(safe-area-inset-top))",paddingLeft:24,paddingRight:24,paddingBottom:12,display:"flex",alignItems:"center",justifyContent:"space-between",position:"sticky",top:0,zIndex:10 }}>
          <div style={{ display:"flex",alignItems:"center",gap:10 }}>
            <div style={{ width:32,height:32,background:"#1a2744",borderRadius:7,display:"flex",alignItems:"center",justifyContent:"center",fontSize:11,color:"#fff",fontWeight:700 }}>SL</div>
            <div><div style={{ fontSize:13,fontWeight:700,color:"#0F172A" }}>SALESLAB AI</div><div style={{ fontSize:10,color:"#94A3B8",letterSpacing:"0.08em" }}>TRAIN · TEST · CLOSE</div></div>
          </div>
          <button onClick={onExit} style={{ fontSize:12,color:"#64748B",background:"#F8FAFC",border:"0.5px solid #D1D9E6",borderRadius:7,padding:"5px 12px",cursor:"pointer" }}>← Back to Dashboard</button>
        </div>
        <div style={{ maxWidth:600,margin:"0 auto",padding:"28px 24px 60px" }}>
          {isChallenged&&challengerScore&&(
            <div style={{ background:s.score>parseInt(challengerScore)?"#F0FDF4":"#EFF6FF",border:`0.5px solid ${s.score>parseInt(challengerScore)?"#BBF7D0":"#BFDBFE"}`,borderRadius:10,padding:"12px 16px",marginBottom:14,textAlign:"center" }}>
              <div style={{ fontSize:14,fontWeight:600,color:s.score>parseInt(challengerScore)?"#16A34A":"#1D4ED8" }}>
                {s.score>parseInt(challengerScore)?`🏆 You beat the challenge! ${s.score} vs ${challengerScore}`:`Challenge score: ${challengerScore}. You scored ${s.score} — try again tomorrow!`}
              </div>
            </div>
          )}
          <div style={{ background:"#EFF6FF",border:"0.5px solid #BFDBFE",borderRadius:10,padding:"12px 16px",display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:14,flexWrap:"wrap",gap:10 }}>
            <div style={{ fontSize:13,color:"#1E3A8A" }}><strong>📸 Scored {s.score} today.</strong> Challenge your team to beat it.</div>
            <div style={{ display:"flex",gap:8 }}>
              <button onClick={()=>copyText(challengePageUrl,"Challenge link copied!")} style={{ background:"#fff",border:"0.5px solid #BFDBFE",borderRadius:7,fontSize:12,fontWeight:500,color:"#1D4ED8",padding:"6px 12px",cursor:"pointer" }}>Copy challenge link</button>
              <button onClick={()=>{ copyText(liMsg,"Post copied! Paste into LinkedIn →"); window.open(liShareUrl,"_blank"); }} style={{ background:"#1D4ED8",color:"#fff",border:"none",borderRadius:7,fontSize:12,fontWeight:500,padding:"6px 12px",cursor:"pointer" }}>💼 Copy + Share →</button>
            </div>
          </div>
          <div style={{ background:"#F8FAFC",border:"0.5px solid #D1D9E6",borderRadius:12,padding:20,marginBottom:14 }}>
            <div style={{ display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16 }}>
              <div style={{ fontSize:10,fontWeight:700,letterSpacing:"0.1em",color:"#94A3B8" }}>SALESLAB AI · SALES IQ</div>
              <div style={{ background:"#DBEAFE",color:"#1D4ED8",borderRadius:20,fontSize:10,fontWeight:600,padding:"3px 10px" }}>{siqRole.name} · Attempt {attemptCount}</div>
            </div>
            <div style={{ display:"flex",alignItems:"flex-end",gap:16,marginBottom:16,paddingBottom:16,borderBottom:"0.5px solid #E2E8F0" }}>
              <div style={{ fontSize:64,fontWeight:700,lineHeight:1,letterSpacing:"-2px",color:scoreColor(s.score).text }}>{s.score}</div>
              <div style={{ paddingBottom:8 }}>
                <div style={{ fontSize:15,fontWeight:600,color:"#0F172A",marginBottom:4 }}>{s.tier}</div>
                <div style={{ fontSize:12,color:"#64748B" }}>{s.rank_pct} today · #{s.rank_num} on leaderboard</div>
              </div>
            </div>
            {isPro?(
              <div style={{ display:"grid",gridTemplateColumns:"1fr 1fr",gap:"6px 24px",marginBottom:16 }}>
                {Object.entries(s.skills).map(([name,val])=>(
                  <div key={name} style={{ display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:13,padding:"5px 0",borderBottom:"0.5px solid #F1F5F9" }}>
                    <span style={{ color:"#64748B" }}>{name}</span>
                    <span style={{ fontWeight:700,color:scoreColor(val).text }}>{val}</span>
                  </div>
                ))}
              </div>
            ):(
              <div style={{ position:"relative",marginBottom:16 }}>
                <div style={{ filter:"blur(4px)",pointerEvents:"none",display:"grid",gridTemplateColumns:"1fr 1fr",gap:"6px 24px" }}>
                  {Object.entries(s.skills).map(([name,val])=>(
                    <div key={name} style={{ display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:13,padding:"5px 0",borderBottom:"0.5px solid #F1F5F9" }}>
                      <span style={{ color:"#64748B" }}>{name}</span><span style={{ fontWeight:700,color:"#1D4ED8" }}>{val}</span>
                    </div>
                  ))}
                </div>
                <div style={{ position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",background:"rgba(248,250,252,0.85)",borderRadius:8,gap:8 }}>
                  <div style={{ fontSize:20 }}>🔒</div>
                  <div style={{ fontSize:13,fontWeight:600,color:"#0F172A" }}>Skill Breakdown · Pro</div>
                  <button onClick={() => { onExit(); }} style={{ background:"#1D4ED8",color:"#fff",border:"none",borderRadius:7,padding:"7px 16px",fontSize:12,fontWeight:600,cursor:"pointer" }}>Unlock Pro →</button>
                </div>
              </div>
            )}
            {isPro&&(
              <div style={{ display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:16 }}>
                <div style={{ background:"#EFF6FF",border:"0.5px solid #BFDBFE",borderRadius:8,padding:"10px 12px" }}>
                  <div style={{ fontSize:10,fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:"#1D4ED8",marginBottom:4 }}>Top strength</div>
                  <div style={{ fontSize:13,fontWeight:600,color:"#0F172A" }}>{s.strength}</div>
                </div>
                <div style={{ background:"#F8FAFC",border:"0.5px solid #E2E8F0",borderRadius:8,padding:"10px 12px" }}>
                  <div style={{ fontSize:10,fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:"#64748B",marginBottom:4 }}>Focus area</div>
                  <div style={{ fontSize:13,fontWeight:600,color:"#0F172A" }}>{s.weakness}</div>
                </div>
              </div>
            )}
            {isPro&&s.tip&&(
              <div style={{ background:"#F8FAFC",border:"0.5px solid #E2E8F0",borderRadius:8,padding:"10px 12px",marginBottom:12 }}>
                <div style={{ fontSize:10,fontWeight:700,color:"#94A3B8",letterSpacing:"0.06em",textTransform:"uppercase",marginBottom:4 }}>Coaching tip</div>
                <div style={{ fontSize:13,color:"#334155",lineHeight:1.5 }}>{s.tip}</div>
              </div>
            )}
            {history.length>1&&(
              <div style={{ borderTop:"0.5px solid #E2E8F0",paddingTop:12,marginBottom:4 }}>
                <div style={{ fontSize:10,fontWeight:700,color:"#94A3B8",letterSpacing:"0.06em",textTransform:"uppercase",marginBottom:8 }}>Your history · {siqRole.name}</div>
                <div style={{ display:"flex",gap:6,alignItems:"flex-end" }}>
                  {history.slice(0,7).reverse().map((h,i)=>(
                    <div key={i} style={{ flex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:3 }}>
                      <div style={{ fontSize:10,fontWeight:600,color:"#1D4ED8" }}>{h.score}</div>
                      <div style={{ width:"100%",borderRadius:3,background:"#1D4ED8",height:`${Math.max(8,(h.score/100)*48)}px`,opacity:i===history.slice(0,7).length-1?1:0.4 }}/>
                      <div style={{ fontSize:9,color:"#94A3B8" }}>{h.date.slice(5)}</div>
                    </div>
                  ))}
                </div>
              </div>
            )}
            <div style={{ display:"flex",alignItems:"center",justifyContent:"space-between",paddingTop:12,borderTop:"0.5px solid #E2E8F0",marginTop:8 }}>
              <div style={{ fontSize:10,fontWeight:700,letterSpacing:"0.08em",color:"#CBD5E1" }}>THESALESLABAI.COM</div>
              <div style={{ display:"flex",alignItems:"center",gap:5,fontSize:11,color:"#94A3B8" }}>
                {streakDays>1?`${streakDays}-day streak 🔥`:""}
                <div style={{ display:"flex",gap:2 }}>{[...Array(Math.min(streakDays,7))].map((_,i)=><div key={i} style={{ width:10,height:10,borderRadius:2,background:"#1D4ED8" }}/>)}</div>
              </div>
            </div>
          </div>
          <div style={{ background:"#fff",border:"0.5px solid #D1D9E6",borderRadius:10,overflow:"hidden",marginBottom:14 }}>
            <div style={{ padding:"10px 16px",borderBottom:"0.5px solid #F1F5F9",display:"flex",alignItems:"center",justifyContent:"space-between" }}>
              <div style={{ fontSize:11,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",color:"#94A3B8" }}>⚡ Today's Sales IQ leaderboard</div>
              <div style={{ fontSize:12,color:"#64748B" }}>Full board →</div>
            </div>
            {allReps.map((rep,i)=>{
              const medal=i===0?"🥇":i===1?"🥈":i===2?"🥉":i+1;
              return(<div key={i} style={{ padding:"9px 16px",display:"flex",alignItems:"center",gap:10,borderTop:"0.5px solid #F1F5F9",background:rep.you?"#EFF6FF":"#fff" }}>
                <div style={{ width:20,fontSize:14 }}>{medal}</div>
                <div style={{ flex:1,fontSize:13,fontWeight:rep.you?600:500,color:rep.you?"#1D4ED8":"#0F172A" }}>{rep.name}{rep.you?" 👈":""}</div>
                <div style={{ fontWeight:700,color:i===0||rep.you?"#1D4ED8":"#94A3B8",fontSize:14 }}>{rep.score}</div>
              </div>);
            })}
          </div>
          <div style={{ background:"#F8FAFC",border:"0.5px solid #E2E8F0",borderRadius:10,padding:14,marginBottom:12 }}>
            <div style={{ fontSize:10,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",color:"#94A3B8",marginBottom:8 }}>Your LinkedIn post — ready to copy</div>
            <div style={{ fontSize:13,color:"#334155",lineHeight:1.6,whiteSpace:"pre-line" }}>{liMsg}</div>
            <button onClick={()=>copyText(liMsg,"LinkedIn post copied!")} style={{ display:"block",width:"100%",marginTop:10,background:"#fff",border:"0.5px solid #D1D9E6",borderRadius:7,fontSize:12,fontWeight:500,color:"#1D4ED8",padding:8,textAlign:"center",cursor:"pointer" }}>Copy LinkedIn post</button>
          </div>
          <div style={{ display:"flex",alignItems:"center",justifyContent:"space-between",background:"#EFF6FF",border:"0.5px solid #BFDBFE",borderRadius:8,padding:"10px 14px",marginBottom:14 }}>
            <div style={{ fontSize:12,fontWeight:600,color:"#1D4ED8" }}>Challenge link</div>
            <div style={{ fontSize:11,color:"#475569",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:180,marginLeft:8 }}>{challengePageUrl.replace("https://","")}</div>
            <div onClick={()=>copyText(challengePageUrl,"Challenge link copied!")} style={{ fontSize:12,fontWeight:600,color:"#1D4ED8",cursor:"pointer",marginLeft:8,flexShrink:0 }}>Copy →</div>
          </div>
          <div style={{ background:"#F0F4FF",border:"0.5px solid #BFDBFE",borderRadius:8,padding:"10px 14px",marginBottom:12,fontSize:12,color:"#1E3A8A",lineHeight:1.5 }}>
            💡 <strong>LinkedIn tip:</strong> Click "Copy post" then paste it into LinkedIn after the page opens — LinkedIn doesn't allow pre-filled text.
          </div>
          <div style={{ display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:10,marginBottom:14 }}>
            {[
              {icon:"🔗",label:"Copy link",     fn:()=>copyText(challengePageUrl,"Link copied!"),                                        primary:true},
              {icon:"💼",label:"Copy + LinkedIn",fn:()=>{ copyText(liMsg,"Post copied! Paste into LinkedIn →"); window.open(liShareUrl,"_blank"); }},
              {icon:"📸",label:"Screenshot",    fn:()=>showToast("Screenshot the result card above!")},
            ].map(btn=>(
              <div key={btn.label} onClick={btn.fn} style={{ background:btn.primary?"#EFF6FF":"#F8FAFC",border:`0.5px solid ${btn.primary?"#BFDBFE":"#E2E8F0"}`,borderRadius:8,padding:"10px 8px",textAlign:"center",cursor:"pointer" }}>
                <div style={{ fontSize:18,marginBottom:4 }}>{btn.icon}</div>
                <div style={{ fontSize:11,fontWeight:500,color:btn.primary?"#1D4ED8":"#0F172A" }}>{btn.label}</div>
              </div>
            ))}
          </div>
          <div style={{ textAlign:"center",fontSize:12,color:"#94A3B8" }}>
            {attemptCount>=3?"Come back tomorrow for harder, personalized scenarios.":"Come back tomorrow for a fresh set of scenarios. Your streak resets at midnight."}
          </div>
        </div>
        {toastMsg&&<div style={{ position:"fixed",bottom:24,left:"50%",transform:"translateX(-50%)",background:"#1D4ED8",color:"#fff",fontSize:13,fontWeight:500,padding:"10px 20px",borderRadius:8,zIndex:200,whiteSpace:"nowrap" }}>{toastMsg}</div>}
      </div>
    );
  }

  // ── Free user daily limit upgrade modal
  if (showFreeUpgrade) {
    const today = new Date().toISOString().split("T")[0];
    const todayEntry = siqGetHistory().find(h => h.date === today);
    const todayScore = todayEntry?.score ?? null;
    return (
      <div style={{ ...fixedScreen, display:"flex", alignItems:"center", justifyContent:"center", padding:20 }}>
        <div style={{ background:"#fff", borderRadius:20, padding:"32px 28px", maxWidth:440, width:"100%", boxShadow:"0 24px 64px rgba(0,0,0,0.15)", border:"1px solid #e2e8f0", fontFamily:"'Inter', sans-serif" }}>
          <div style={{ textAlign:"center", marginBottom:24 }}>
            <div style={{ fontSize:40, marginBottom:12 }}>⚡</div>
            <div style={{ fontSize:20, fontWeight:800, color:"#0f172a", marginBottom:8, letterSpacing:"-0.02em" }}>You've used your free attempt today</div>
            <div style={{ fontSize:13.5, color:"#64748b", lineHeight:1.65 }}>
              Free users get <strong style={{ color:"#0f172a" }}>1 Sales IQ test per day</strong>. Your free attempt resets at midnight. Upgrade to Pro for unlimited daily retakes, full skill breakdown, and your streak tracker.
            </div>
          </div>

          {todayScore !== null && (
            <div style={{ padding:"14px 18px", borderRadius:12, background:scoreColor(todayScore).bg, border:`1px solid ${scoreColor(todayScore).border}`, marginBottom:20, display:"flex", alignItems:"center", gap:14 }}>
              <div style={{ textAlign:"center", minWidth:52 }}>
                <div style={{ fontSize:32, fontWeight:800, color:scoreColor(todayScore).text, lineHeight:1 }}>{todayScore}</div>
                <div style={{ fontSize:10, color:"#94a3b8" }}>/100</div>
              </div>
              <div>
                <div style={{ fontSize:13, fontWeight:700, color:"#0f172a", marginBottom:3 }}>{scoreColor(todayScore).label} — today's score</div>
                <div style={{ fontSize:11, color:"#64748b" }}>Share it before upgrading 👇</div>
              </div>
            </div>
          )}

          {todayScore !== null && (
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:8, marginBottom:20 }}>
              <button onClick={() => {
                const url = `https://thesaleslabai.com/challenge?s=${todayScore}&r=Rep`;
                if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(url).catch(()=>{}); }
                else { try { const ta=document.createElement("textarea"); ta.value=url; ta.style.cssText="position:fixed;top:-9999px;left:-9999px;"; document.body.appendChild(ta); ta.focus(); ta.select(); document.execCommand("copy"); document.body.removeChild(ta); } catch {} }
                showToast("Challenge link copied!");
              }} style={{ padding:"10px", borderRadius:9, background:"#fff", border:"1px solid #e2e8f0", color:"#1d4ed8", fontSize:13, fontWeight:600, cursor:"pointer" }}>
                🔗 Copy challenge link
              </button>
              <button onClick={() => {
                const url = `https://thesaleslabai.com/challenge?s=${todayScore}&r=Rep`;
                const post = `Just scored ${todayScore}/100 on the SalesLab AI Sales IQ challenge.\n\nThink you can beat it?\n${url}\n\n#SalesIQ #SalesTraining #SalesLab`;
                if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(post).catch(()=>{}); }
                else { try { const ta=document.createElement("textarea"); ta.value=post; ta.style.cssText="position:fixed;top:-9999px;left:-9999px;"; document.body.appendChild(ta); ta.focus(); ta.select(); document.execCommand("copy"); document.body.removeChild(ta); } catch {} }
                window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`, "_blank");
                showToast("Post copied! Paste into LinkedIn →");
              }} style={{ padding:"10px", borderRadius:9, background:"#1d4ed8", border:"none", color:"#fff", fontSize:13, fontWeight:600, cursor:"pointer" }}>
                💼 Copy + LinkedIn
              </button>
            </div>
          )}

          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:10, marginBottom:16 }}>
            {[
              { label:"Pro", price:"$29/mo", desc:"Unlimited daily tests, full skill breakdown, streak tracker", color:"#1e293b", href:`https://www.paypal.com/webapps/billing/plans/subscribe?plan_id=P-5Y1401853D764390CNG4Z6GQ` },
              { label:"Team", price:"$199/mo", desc:"Everything in Pro for up to 10 reps + manager dashboard", color:"#1d4ed8", href:`https://www.paypal.com/webapps/billing/plans/subscribe?plan_id=P-2BB96861PG443164MNG4Z7SA` },
            ].map(t => (
              <a key={t.label} href={t.href} target="_blank" rel="noreferrer" style={{ textDecoration:"none" }}>
                <div style={{ padding:"14px 16px", borderRadius:12, background:t.color, cursor:"pointer", boxSizing:"border-box" }}>
                  <div style={{ fontSize:13, fontWeight:700, color:"#fff", marginBottom:2 }}>{t.label}</div>
                  <div style={{ fontSize:16, fontWeight:800, color:"#fff", marginBottom:6 }}>{t.price}</div>
                  <div style={{ fontSize:11, color:"rgba(255,255,255,0.7)", lineHeight:1.5 }}>{t.desc}</div>
                </div>
              </a>
            ))}
          </div>

          <a href="https://docs.google.com/forms/d/e/1FAIpQLSeOLOobsAywU9nZ3j-s1BC8DdEROWTwzNgBAfkRP5OugFVSVw/viewform?usp=header" target="_blank" rel="noreferrer" style={{ textDecoration:"none", display:"block", marginBottom:12 }}>
            <div style={{ padding:"12px 16px", borderRadius:10, background:"#f8fafc", border:"1px solid #e2e8f0", display:"flex", alignItems:"center", justifyContent:"space-between" }}>
              <div>
                <div style={{ fontSize:12, fontWeight:700, color:"#0f172a" }}>🏢 Enterprise · $699/mo</div>
                <div style={{ fontSize:11, color:"#64748b" }}>11–50 seats · white-label · custom AI personas</div>
              </div>
              <div style={{ fontSize:12, fontWeight:600, color:"#1d4ed8" }}>Book demo →</div>
            </div>
          </a>

          <div style={{ textAlign:"center", fontSize:11, color:"#94a3b8", marginBottom:14 }}>
            🔄 Your free attempt resets at midnight tonight.
          </div>
          <button onClick={onExit} style={{ width:"100%", padding:"11px", borderRadius:10, background:"transparent", border:"1px solid #e2e8f0", color:"#94a3b8", fontSize:13, cursor:"pointer", fontFamily:"'Inter', sans-serif" }}>
            Back to Dashboard
          </button>
        </div>
        {toastMsg && <div style={{ position:"fixed", bottom:24, left:"50%", transform:"translateX(-50%)", background:"#1D4ED8", color:"#fff", fontSize:13, fontWeight:500, padding:"10px 20px", borderRadius:8, zIndex:200, whiteSpace:"nowrap" }}>{toastMsg}</div>}
      </div>
    );
  }

  return null;
}

// ── Sales IQ Dashboard Card (shown on home screen) ───────────────────────────
function SalesIQDashboardCard({ onTakeTest, isPro, onUpgrade }) {
  const history = siqGetHistory();
  const lastEntry = history[0] || null;
  const lastScore = lastEntry?.score ?? null;
  const lastTier  = lastEntry?.tier ?? null;
  const streak    = siqGetStreak();
  const hasScore  = lastScore !== null;

  const today = new Date().toISOString().split("T")[0];
  const playedToday = history.some(h => h.date === today);
  const canPlay = isPro || !playedToday;

  return (
    <div style={{ background:"#fff", border:"0.5px solid #D1D9E6", borderRadius:12, overflow:"hidden", marginBottom:16, fontFamily:"'Inter', sans-serif" }}>

      {/* Header row */}
      <div style={{ padding:"16px 18px 14px", borderBottom:"0.5px solid #F1F5F9", display:"flex", alignItems:"flex-start", justifyContent:"space-between", gap:12 }}>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontSize:10, fontWeight:600, letterSpacing:"0.1em", color:"#94A3B8", textTransform:"uppercase", marginBottom:3 }}>Daily challenge</div>
          <div style={{ fontSize:15, fontWeight:700, color:"#0F172A", marginBottom:2 }}>
            Sales IQ Assessment
            {!isPro && <span style={{ background:"#EFF6FF", color:"#1D4ED8", fontSize:10, fontWeight:600, padding:"2px 8px", borderRadius:10, marginLeft:8, border:"0.5px solid #BFDBFE" }}>Free · 1/day</span>}
            {isPro  && <span style={{ background:"#DBEAFE", color:"#1D4ED8", fontSize:10, fontWeight:600, padding:"2px 8px", borderRadius:10, marginLeft:8 }}>Pro · Unlimited</span>}
          </div>
          <div style={{ fontSize:12, color:"#64748B" }}>
            {isPro ? "Unlimited daily attempts · Full skill breakdown" : "5 questions · 1 free attempt per day · See where you rank"}
          </div>
        </div>
        {/* Header right: take button OR streak dots (no upgrade button here) */}
        {canPlay ? (
          <button onClick={onTakeTest} style={{ background:"#1D4ED8", color:"#fff", border:"none", borderRadius:8, padding:"9px 16px", fontSize:13, fontWeight:600, cursor:"pointer", whiteSpace:"nowrap", flexShrink:0 }}>
            {hasScore && isPro ? "Retake →" : "Take test →"}
          </button>
        ) : (
          /* Played today — show streak dots instead of an upgrade button */
          <div style={{ display:"flex", flexDirection:"column", alignItems:"flex-end", gap:4, flexShrink:0 }}>
            <div style={{ display:"flex", gap:3 }}>
              {[...Array(7)].map((_,i) => (
                <div key={i} style={{ width:14, height:14, borderRadius:3, background:i<(streak||0)?"#1D4ED8":i===(streak||0)?"#93C5FD":"#F1F5F9" }}/>
              ))}
            </div>
            <div style={{ fontSize:10, color:"#94A3B8" }}>{streak>1?`${streak}-day streak 🔥`:"Day 1"}</div>
          </div>
        )}
      </div>

      {/* Score row */}
      {hasScore && (
        <>
          <div style={{ padding:"12px 18px", display:"flex", alignItems:"center", gap:16, borderBottom:"0.5px solid #F1F5F9" }}>
            <div style={{ textAlign:"center", minWidth:60 }}>
              <div style={{ fontSize:36, fontWeight:700, color:scoreColor(lastScore).text, lineHeight:1 }}>{lastScore}</div>
              <div style={{ fontSize:10, color:"#94A3B8" }}>/100</div>
            </div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:13, fontWeight:600, color:"#0F172A", marginBottom:4 }}>{lastTier}</div>
              <div style={{ fontSize:12, color:"#64748B" }}>
                {isPro ? "Take today's test to update your rank" : playedToday ? "Come back tomorrow for a new set of questions" : "Take today's test to update your rank"}
              </div>
            </div>
            {isPro && (
              <div style={{ display:"flex", flexDirection:"column", alignItems:"flex-end", gap:4 }}>
                <div style={{ display:"flex", gap:3 }}>
                  {[...Array(7)].map((_,i) => <div key={i} style={{ width:14, height:14, borderRadius:3, background:i<(streak||0)?"#1D4ED8":i===(streak||0)?"#93C5FD":"#F1F5F9" }}/>)}
                </div>
                <div style={{ fontSize:10, color:"#94A3B8" }}>{streak>1?`${streak}-day streak 🔥`:"Day 1"}</div>
              </div>
            )}
          </div>

          {/* Share row */}
          <div style={{ padding:"10px 18px", display:"flex", alignItems:"center", justifyContent:"space-between", background:"#EFF6FF", borderTop:"0.5px solid #BFDBFE" }}>
            <div style={{ display:"flex", alignItems:"center", gap:8 }}>
              <div style={{ fontSize:16 }}>📸</div>
              <div style={{ fontSize:12, color:"#1E3A8A" }}><strong>Scored {lastScore}.</strong> Challenge someone to beat it.</div>
            </div>
            <div style={{ display:"flex", gap:8 }}>
              <button onClick={() => {
                const url = `https://thesaleslabai.com/challenge?s=${lastScore}&r=Rep`;
                if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(url).catch(()=>{}); }
                else { try { const ta=document.createElement("textarea"); ta.value=url; ta.style.cssText="position:fixed;top:-9999px;left:-9999px;"; document.body.appendChild(ta); ta.focus(); ta.select(); document.execCommand("copy"); document.body.removeChild(ta); } catch {} }
              }} style={{ background:"#fff", border:"0.5px solid #BFDBFE", borderRadius:7, fontSize:12, fontWeight:500, color:"#1D4ED8", padding:"6px 12px", cursor:"pointer" }}>Copy link</button>
              <button onClick={() => {
                const url = `https://thesaleslabai.com/challenge?s=${lastScore}&r=Rep`;
                const post = `Just scored ${lastScore}/100 on the SalesLab AI Sales IQ challenge.\n\nThink you can beat it?\n${url}\n\n#SalesIQ #SalesTraining #SalesLab`;
                if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(post).catch(()=>{}); }
                else { try { const ta=document.createElement("textarea"); ta.value=post; ta.style.cssText="position:fixed;top:-9999px;left:-9999px;"; document.body.appendChild(ta); ta.focus(); ta.select(); document.execCommand("copy"); document.body.removeChild(ta); } catch {} }
                window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`, "_blank");
              }} style={{ background:"#1D4ED8", color:"#fff", border:"none", borderRadius:7, fontSize:12, fontWeight:500, padding:"6px 12px", cursor:"pointer" }}>Copy + LinkedIn →</button>
            </div>
          </div>
        </>
      )}

      {/* No score yet */}
      {!hasScore && (
        <div style={{ padding:"20px 18px", display:"flex", alignItems:"center", justifyContent:"center", flexDirection:"column", gap:8 }}>
          <div style={{ fontSize:13, color:"#64748B" }}>You haven't taken today's test yet.</div>
          <div style={{ fontSize:12, color:"#94A3B8" }}>5 questions · ~3 minutes · Score revealed instantly</div>
        </div>
      )}

      {/* Free user played today — soft text nudge, no button */}
      {!isPro && playedToday && (
        <div style={{ padding:"10px 18px", background:"#F8FAFC", borderTop:"0.5px solid #F1F5F9", display:"flex", alignItems:"center", justifyContent:"space-between", gap:12 }}>
          <div style={{ fontSize:11, color:"#64748B", lineHeight:1.5 }}>
            🔒 1 free attempt used today. Come back tomorrow or{" "}
            <span onClick={onUpgrade} style={{ color:"#1D4ED8", fontWeight:600, cursor:"pointer", textDecoration:"underline" }}>upgrade for unlimited</span>.
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Daily Coaching Tip Card ──────────────────────────────────────────────────
const DAILY_TIPS = [
  { icon: "🎯", category: "Closing",         tip: "The close starts in discovery. The rep who asks the best questions never has to push for the close — the buyer closes themselves." },
  { icon: "💬", category: "Objection",       tip: "When a buyer says 'I need to think about it', they're not thinking about your product. They're thinking about a concern you haven't addressed yet. Find it." },
  { icon: "🔍", category: "Discovery",       tip: "Ask one more question than you think you need to. The third follow-up question is almost always where the real buying motive lives." },
  { icon: "📞", category: "Follow-Up",       tip: "The best follow-up references something specific from your last conversation. 'Checking in' is not a follow-up — it's noise." },
  { icon: "💰", category: "Pricing",         tip: "Never defend your price. Expand the value until the price feels small by comparison. Defending price signals doubt." },
  { icon: "🧠", category: "Mindset",         tip: "Rejection is data, not judgment. Every 'no' narrows down who your real buyers are. Track them, study them, adjust." },
  { icon: "⚡", category: "Urgency",         tip: "Manufactured urgency destroys trust. Real urgency comes from helping the buyer see what inaction costs them — in dollars, time, or risk." },
  { icon: "🤝", category: "Trust",           tip: "Slow down to build trust faster. Reps who rush the pitch lose deals. Reps who ask good questions and listen win them." },
  { icon: "📊", category: "Negotiation",     tip: "Never give a concession without getting something in return. Even a small ask ('if we do X, can we get your signature this week?') preserves value." },
  { icon: "🎭", category: "Personas",        tip: "Analytical buyers need data before emotion. Lead with numbers and ROI, then let the emotional benefit land as confirmation — not the hook." },
  { icon: "📱", category: "Prospecting",     tip: "Cold outreach is a volume game only if your message is generic. Personalization at scale beats spray-and-pray every time." },
  { icon: "🏆", category: "Performance",     tip: "Top closers review their lost deals as carefully as their wins. The patterns in your losses are worth more than any training script." },
  { icon: "🔄", category: "Stalled Deals",  tip: "A deal that goes dark needs a pattern interrupt, not another follow-up. Try a shorter message with a direct question: 'Is this still a priority?'" },
  { icon: "👂", category: "Listening",       tip: "Talk less than 50% of the time on a discovery call. The buyer's words are your closing ammunition — let them give it to you." },
  { icon: "🚀", category: "Onboarding",      tip: "The best time to ask for a referral is during onboarding, when excitement is highest. Most reps wait until renewal — that's too late." },
  { icon: "📝", category: "Preparation",     tip: "Know three things before every call: what they care about, what could stop this deal, and what your next step will be regardless of outcome." },
  { icon: "💡", category: "Reframing",       tip: "When a buyer compares you to a cheaper competitor, never attack the competition. Ask: 'What's the cost of that difference if the cheaper option doesn't deliver?'" },
  { icon: "🎯", category: "Pipeline",        tip: "A healthy pipeline has 3x your quota. Anything less and you're hoping, not selling. Build it before you need it." },
  { icon: "⏱️", category: "Time Management", tip: "Protect your peak selling hours. Admin, CRM updates, and email can happen at off-peak times. Your best energy belongs on live conversations." },
  { icon: "🔑", category: "Authority",       tip: "Always find the economic buyer. A champion who can't sign can't close. Ask early: 'Who else needs to be part of this decision?'" },
  { icon: "📈", category: "Growth",          tip: "The rep who practices 30 minutes a day compounds faster than the one who trains once a month. Frequency beats intensity in skill development." },
  { icon: "🤔", category: "Curiosity",       tip: "Lead with curiosity, not product knowledge. The most dangerous sales call is one where the rep talks more than they listen." },
  { icon: "🛡️", category: "Objection Prep",  tip: "Write down every objection you've heard in the last 30 days. If you can't answer each one in under 10 seconds, that's your practice list." },
  { icon: "🌟", category: "Differentiation", tip: "If you can't explain your differentiation in one sentence without using the word 'quality', you don't have a differentiation — you have a feature list." },
  { icon: "📅", category: "Next Steps",      tip: "Every call should end with a specific next step that has a date attached. 'I'll follow up soon' is how deals die." },
  { icon: "💪", category: "Confidence",      tip: "Confidence in sales comes from preparation, not personality. The rep who has practiced 100 objections is naturally more confident than the one who hasn't." },
  { icon: "🔮", category: "Forecasting",     tip: "If you can't name the economic buyer, the timeline, and the next step — it's not in your pipeline. It's on your wish list." },
  { icon: "🎪", category: "Demo",            tip: "Don't demo features. Demo outcomes. Show them what their world looks like after they buy, not how many buttons you have." },
];

function DailyTipCard() {
  // Pick a tip based on day of year so it rotates daily but is consistent for the day
  const dayOfYear = Math.floor((Date.now() - new Date(new Date().getFullYear(), 0, 0)) / 86400000);
  const tip = DAILY_TIPS[dayOfYear % DAILY_TIPS.length];

  return (
    <div style={{ background:"#fff", border:"0.5px solid #D1D9E6", borderRadius:12, padding:"16px 18px", marginBottom:16, fontFamily:"'Inter', sans-serif" }}>
      <div style={{ display:"flex", alignItems:"center", gap:8, marginBottom:10 }}>
        <span style={{ fontSize:18 }}>{tip.icon}</span>
        <div style={{ fontSize:10, fontWeight:700, letterSpacing:"0.1em", color:"#94A3B8", textTransform:"uppercase" }}>Today's coaching tip · {tip.category}</div>
      </div>
      <div style={{ fontSize:13.5, color:"#1E293B", lineHeight:1.65, fontStyle:"italic" }}>"{tip.tip}"</div>
    </div>
  );
}

// ─── Main App ──────────────────────────────────────────────────────────────────

window.SalesLabApp = function SalesLabApp() {
  const [authTier, setAuthTier] = useState("loggedout");
  const [isPro, setIsPro] = useState(false);
  const [isTeam, setIsTeam] = useState(false);
  const [authLoading, setAuthLoading] = useState(true);
  const [currentUser, setCurrentUser] = useState(null);
  const [teamView, setTeamView] = useState("dashboard");
  const [showPaywall, setShowPaywall] = useState(false);
  const [showUpgradePrompt, setShowUpgradePrompt] = useState(false);
  const [upgradeFeatureName, setUpgradeFeatureName] = useState("");
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [activeSystem, setActiveSystem] = useState(1);
  const [activeSection, setActiveSection] = useState(null); // null = home/chat, number = section page
  const [showAffiliate, setShowAffiliate] = useState(false);
  const [showSupport, setShowSupport] = useState(false);
  const [showOwnerAdmin, setShowOwnerAdmin] = useState(false);
  const [showChangelog, setShowChangelog] = useState(false);
  const [showGame, setShowGame] = useState(false);
  const [showLeaderboard, setShowLeaderboard] = useState(false);
  const [showProfitEngine, setShowProfitEngine] = useState(false);
  const [showSalesIQ, setShowSalesIQ] = useState(false);
  const [siqLastScore, setSiqLastScore] = useState(null);
  const [siqLastTier, setSiqLastTier] = useState(null);
  const [siqStreak, setSiqStreak] = useState(7);
  const [promptInputModal, setPromptInputModal] = useState(null); // { config } | null
  const [installPrompt, setInstallPrompt] = useState(null);
  const [sectionIndustry, setSectionIndustry] = useState(null);
  const [sectionRole, setSectionRole] = useState(null);
  const [sectionEnv, setSectionEnv] = useState(null);

  // ── Usage restriction state ──
  const [usageData, setUsageData] = useState(null);
  const [showFreeSessionLimit, setShowFreeSessionLimit] = useState(false);
  const [showProTokenWarning, setShowProTokenWarning] = useState(false);
  const [showProTokenLimit, setShowProTokenLimit] = useState(false);
  const [tokenWarningShownThisMonth, setTokenWarningShownThisMonth] = useState(false);
  const [showInstallBanner, setShowInstallBanner] = useState(false);
  const [showIOSBanner, setShowIOSBanner] = useState(false);
  const [swUpdateReady, setSwUpdateReady] = useState(false);
  const bottomRef = useRef(null);
  const textareaRef = useRef(null);

  useEffect(() => {
    const initAuth = async () => {
      try {
        let session = supabase.auth.handleCallback();
        if (!session) session = supabase.auth.getSession();
        if (!session?.access_token) { setAuthLoading(false); return; }
        const user = await supabase.auth.getUser(session.access_token);
        if (!user?.id) { setAuthLoading(false); return; }
        await supabase.db.upsertUser(user.id, user.email, session.access_token);
        const { data: profile } = await sbDB.select("profiles", { id: user.id }, { select: "id,email,role,company_id,plan_id,status", single: true });
        const tier = await supabase.db.getUserTier(user.id, session.access_token);
        setCurrentUser({
          id: user.id,
          email: user.email,
          role: profile?.role || "member",
          company_id: profile?.company_id || null,
          plan_id: profile?.plan_id || null,
          status: profile?.status || "active",
        });
        setAuthTier(tier);
        const isProTier = tier === "pro" || tier === "team";
        setIsPro(isProTier);
        setIsTeam(tier === "team"); // Correctly reflect team status
        // Load usage data
        try {
          let usage = await usageDB.getUsage(user.id);
          if (!usage) { await usageDB.initUsage(user.id); usage = await usageDB.getUsage(user.id); }
          setUsageData(usage);
        } catch (e) { console.warn("[Usage] Failed to load:", e); }
        setTimeout(() => { if (window.__processTeamJoin) window.__processTeamJoin({ id: user.id, email: user.email }); }, 100);
      } catch (err) {
        console.warn("[Auth] Init error:", err);
      } finally {
        setAuthLoading(false);
      }
    };
    initAuth();
  }, []);


  // ── Periodic subscription re-check (catches cancellations without logout)
  useEffect(() => {
    if (!currentUser) return;
    const recheckTier = async () => {
      try {
        const session = supabase.auth.getSession();
        if (!session?.access_token) return;
        const tier = await supabase.db.getUserTier(currentUser.id, session.access_token);
        console.log("[Auth] Resolved tier on recheck:", tier);
        setIsPro(tier === "pro" || tier === "team");
        setIsTeam(tier === "team");
        setAuthTier(tier);
      } catch {}
    };
    const interval = setInterval(recheckTier, 5 * 60 * 1000);
    const onVisibility = () => { if (document.visibilityState === "visible") recheckTier(); };
    document.addEventListener("visibilitychange", onVisibility);
    return () => {
      clearInterval(interval);
      document.removeEventListener("visibilitychange", onVisibility);
    };
  }, [currentUser]);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const teamToken = params.get("team");
    if (teamToken) {
      sessionStorage.setItem("pending_team_token", teamToken);
      window.history.replaceState({}, "", "/");
    }
  }, []);

  window.__processTeamJoin = async (user) => {
    const token = sessionStorage.getItem("pending_team_token");
    if (!token || !user) return;
    sessionStorage.removeItem("pending_team_token");
    try {
      const res = await fetch("https://lvucoalaoufpxbkljzis.supabase.co/functions/v1/team-join", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Authorization": `Bearer ${SUPABASE_ANON_KEY}` },
        body: JSON.stringify({ token, userId: user.id, userEmail: user.email }),
      });
      const data = await res.json();
      if (data.success) {
        const tier = await supabase.db.getUserTier(user.id);
        const hasPaidAccess = tier === "pro" || tier === "team";
        setAuthTier(tier || "free");
        setIsPro(hasPaidAccess);
        const welcomeMsg = {
          role: "assistant",
          content: hasPaidAccess
            ? `Welcome to **${data.teamName}**! 🎉\n\nYour manager has added you to the team and your paid access is now active.\n\nType: *"Start my onboarding program"* to begin, or tell me what you sell and your biggest challenge right now.`
            : `Welcome to **${data.teamName}**! 🎉\n\nYour invite was accepted, but we're still waiting for billing confirmation before unlocking paid access.\n\nIf your access doesn't update shortly, contact ${BRAND_CONFIG.supportEmail}.`
        };
        setMessages([welcomeMsg]);
      }
    } catch (e) {
      console.error("Team join error:", e);
    }
  };

  const handleSignOut = async () => {
    await supabase.auth.signOut();
    setAuthTier("loggedout");
    setIsPro(false);
    setIsTeam(false);
    setShowOwnerAdmin(false);
    setCurrentUser(null);
    setMessages([]);
  };

  const requirePro = (featureName) => {
    if (isPro) return true;
    setUpgradeFeatureName(featureName);
    setShowUpgradePrompt(true);
    return false;
  };


  // Handle payment redirect back to app (?pro=true / ?team=true / ?topup=true)
  // Also handle Sales IQ challenge links (?iq=slug)
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const iqParam = params.get("iq");
    if (iqParam) {
      // Auto-open Sales IQ — challenge link clicked
      setTimeout(() => setShowSalesIQ(true), 600);
    }
    const hasPro = params.get("pro") === "true";
    const hasTeam = params.get("team") === "true";
    const hasTopup = params.get("topup") === "true";
    if (!hasPro && !hasTeam && !hasTopup) return;

    // Clean URL so refreshing doesn't re-trigger
    window.history.replaceState({}, document.title, "/app");

    if (hasTopup) {
      setMessages([{
        role: "assistant",
        content: "✅ **Token top-up successful!** Your 300,000 tokens have been added and are valid for 30 days. Keep training! 🚀"
      }]);
      return;
    }

    const tier = hasTeam ? "team" : "pro";
    setMessages([{
      role: "assistant",
      content: "Payment received for **" + BRAND_CONFIG.appName + " " + (tier === "team" ? "Team" : "Pro") + "**.\n\nWe're waiting for billing confirmation before unlocking paid access. Your account will update automatically as soon as that sync completes.\n\nIf access still hasn't updated after a few minutes, contact " + BRAND_CONFIG.supportEmail + "."
    }]);
  }, []);

  useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messages, loading]);

  useEffect(() => {
    if ("serviceWorker" in navigator) {
      navigator.serviceWorker.register("/service-worker.js").then((reg) => {
        reg.addEventListener("updatefound", () => {
          const newWorker = reg.installing;
          newWorker?.addEventListener("statechange", () => {
            if (newWorker.state === "installed" && navigator.serviceWorker.controller) setSwUpdateReady(true);
          });
        });
      }).catch((err) => console.warn("[PWA] SW registration failed:", err));
    }
    const handleInstallPrompt = (e) => { e.preventDefault(); setInstallPrompt(e); setShowInstallBanner(true); };
    window.addEventListener("beforeinstallprompt", handleInstallPrompt);
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
    const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
    const isStandalone = window.matchMedia("(display-mode: standalone)").matches || window.navigator.standalone === true;
    if (isIOS && isSafari && !isStandalone) setTimeout(() => setShowIOSBanner(true), 2500);
    return () => window.removeEventListener("beforeinstallprompt", handleInstallPrompt);
  }, []);

  // ── Fix orientation change resizing (keyboard handled by viewport meta in HTML) ─
  useEffect(() => {
    const setAppHeight = () => {
      // Use innerHeight only on orientation change (not keyboard events)
      document.documentElement.style.setProperty("--app-height", `${window.innerHeight}px`);
    };
    setAppHeight();
    window.addEventListener("orientationchange", () => setTimeout(setAppHeight, 300));
    return () => window.removeEventListener("orientationchange", setAppHeight);
  }, []);

  const handleInstallClick = async () => {
    if (!installPrompt) return;
    installPrompt.prompt();
    const { outcome } = await installPrompt.userChoice;
    if (outcome === "accepted") setShowInstallBanner(false);
    setInstallPrompt(null);
  };

  const handleSwUpdate = () => { navigator.serviceWorker.controller?.postMessage({ type: "SKIP_WAITING" }); window.location.reload(); };

  if (authLoading) {
    return (
      <div style={{ position: "fixed", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", background: "#ffffff", fontFamily: "'Inter', sans-serif", flexDirection: "column", gap: 20 }}>
        <style>{`@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.4} }`}</style>
        <img src={BRAND_CONFIG.logoPath} alt={BRAND_CONFIG.appName} style={{ width: 88, height: 88, borderRadius: 20, objectFit: "cover" }} />
        <div style={{ textAlign: "center" }}>
          <div style={{ fontSize: 18, fontWeight: 800, color: "#0f172a", letterSpacing: "0.06em", marginBottom: 6 }}>{BRAND_CONFIG.appName.toUpperCase()}</div>
          <div style={{ fontSize: 11, color: "#94a3b8", letterSpacing: "0.2em", animation: "pulse 1.6s ease-in-out infinite" }}>{BRAND_CONFIG.tagline}</div>
        </div>
      </div>
    );
  }

  if (authTier === "loggedout") return <LoginScreen />;

  if (currentUser && currentUser.status && currentUser.status !== "active") {
    const isSuspended = currentUser.status === "suspended";
    const isInactive = currentUser.status === "inactive";
    return (
      <div style={{
        minHeight: "100svh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        background: "linear-gradient(135deg, #f8fafc 0%, #eef2ff 100%)",
        padding: 24,
        fontFamily: "'Inter', sans-serif",
      }}>
        <div style={{
          width: "min(520px, 100%)",
          background: "#ffffff",
          borderRadius: 20,
          border: "1px solid #e2e8f0",
          boxShadow: "0 20px 60px rgba(15,23,42,0.12)",
          padding: 28,
        }}>
          <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: "0.14em", color: isSuspended ? "#b91c1c" : "#475569", marginBottom: 10 }}>
            ACCOUNT {String(currentUser.status || "").toUpperCase()}
          </div>
          <div style={{ fontSize: 26, fontWeight: 800, color: "#0f172a", marginBottom: 10 }}>
            {isSuspended ? "Access restricted" : isInactive ? "Account inactive" : "Account unavailable"}
          </div>
          <div style={{ fontSize: 14, color: "#64748b", lineHeight: 1.7, marginBottom: 18 }}>
            {isSuspended
              ? "Your account has been restricted by an administrator. Contact support if you believe this was a mistake."
              : isInactive
                ? "Your account is currently inactive. Contact support or your team administrator to restore access."
                : "Your account is not currently allowed to use the app. Contact support to restore access."}
          </div>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            <a href={`mailto:${BRAND_CONFIG.supportEmail}`} style={{ textDecoration: "none" }}>
              <button style={{ padding: "10px 16px", borderRadius: 10, border: "none", background: "#0f172a", color: "#fff", fontSize: 13, fontWeight: 700, cursor: "pointer" }}>
                Contact Support
              </button>
            </a>
            <button onClick={handleSignOut} style={{ padding: "10px 16px", borderRadius: 10, border: "1px solid #dbe3ee", background: "#fff", color: "#475569", fontSize: 13, fontWeight: 700, cursor: "pointer" }}>
              Sign out
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (isTeam) return <TeamDashboard teamView={teamView} setTeamView={setTeamView} onExit={() => setIsTeam(false)} currentUser={currentUser} supabase={supabase} />;

  const SIDEBAR = isPro ? PRO_SIDEBAR : FREE_SIDEBAR;
  const QUICK_PROMPTS = isPro ? PRO_QUICK_PROMPTS : FREE_QUICK_PROMPTS;

  // ── Dynamic system prompt — append user context if set ──────────────────────
  const buildSystemPrompt = () => {
    const base = isPro ? PRO_SYSTEM_PROMPT : FREE_SYSTEM_PROMPT;
    const ind = SECTION_INDUSTRIES.find(i => i.id === sectionIndustry);
    const rol = SECTION_ROLES.find(r => r.id === sectionRole);
    const env = SECTION_ENVS.find(e => e.id === sectionEnv);
    if (!ind && !rol && !env) return base;
    const parts = [];
    if (ind) parts.push(`Industry: ${ind.label}`);
    if (rol) parts.push(`Role: ${rol.label}`);
    if (env) parts.push(`Environment: ${env.label}`);
    const ctx = `\n\n── USER CONTEXT (apply to every response) ──\nThis user has identified themselves as:\n${parts.join("\n")}\nTailor ALL responses — objection handling, roleplays, scripts, coaching, examples, and language — specifically to this context. Use industry-specific terminology, realistic scenarios, and relevant buyer types for their setting. Never give generic advice when you have this context.`;
    return base + ctx;
  };

  const sendMessage = async (text) => {
    const msg = (text || input).trim();
    if (!msg || loading) return;

    // ── PLACEHOLDER PROMPT INTERCEPT ─────────────────────────────────────────
    // All commands in PROMPT_INPUT_CONFIGS open the modal — unless real content is already present.
    const interceptKeys = Object.keys(PROMPT_INPUT_CONFIGS);
    const matchedKey = interceptKeys.find(key => msg.toUpperCase().startsWith(key.toUpperCase()));
    if (matchedKey) {
      // Extract any pre-filled content after the command prefix
      const prefilled = msg.slice(matchedKey.length).trim().replace(/^\[.*\]$/, "");
      // If there's real content after the prefix, send directly — don't re-open the modal
      if (prefilled && prefilled.length > 0) {
        // fall through to send
      } else {
        setPromptInputModal({ config: PROMPT_INPUT_CONFIGS[matchedKey], prefilled });
        setInput("");
        return;
      }
    }

    // ── FREE USER CHECKS ──────────────────────────────────────────────────────
    if (!isPro && currentUser) {
      // Check daily prompt limit
      const dayStart = getDayStart();
      const promptsToday = (usageData?.day_start === dayStart ? usageData?.prompts_today : 0) || 0;
      if (promptsToday >= FREE_MAX_PROMPTS_PER_DAY) {
        setShowFreeSessionLimit(true);
        return;
      }
    }

    // ── PRO/TEAM USER TOKEN CHECKS ────────────────────────────────────────────
    if (isPro && currentUser) {
      const monthStart = getMonthStart();
      const tokensUsed = (usageData?.month_start === monthStart ? usageData?.tokens_used_this_month : 0) || 0;
      const topupActive = usageData?.topup_tokens_remaining > 0 &&
        usageData?.topup_expires_at && new Date() < new Date(usageData.topup_expires_at);
      const effectiveLimit = topupActive
        ? PRO_MAX_TOKENS_PER_MONTH + (usageData?.topup_tokens_remaining || 0)
        : PRO_MAX_TOKENS_PER_MONTH;

      if (tokensUsed >= effectiveLimit) {
        setShowProTokenLimit(true);
        return;
      }
      if (!tokenWarningShownThisMonth && tokensUsed >= effectiveLimit - PRO_TOKEN_WARNING_THRESHOLD) {
        setShowProTokenWarning(true);
        setTokenWarningShownThisMonth(true);
        // Allow the message to proceed after warning shown
      }
    }

    // ── SEND ──────────────────────────────────────────────────────────────────
    const newMsgs = [...messages, { role: "user", content: msg }];
    setMessages(newMsgs); // display shows clean message
    setInput("");
    if (textareaRef.current) textareaRef.current.style.height = "auto";
    setLoading(true);

    // Build context-prefixed messages for API — user sees clean msg, AI gets full context
    const ctx = buildSectionContext(sectionIndustry, sectionRole, sectionEnv);
    const apiMsgs = newMsgs.map((m, i) => {
      // Only prefix the latest user message, and only if context is set and not already prefixed
      if (i === newMsgs.length - 1 && m.role === "user" && ctx && !m.content.startsWith("[")) {
        return { role: "user", content: ctx + m.content };
      }
      return { role: m.role, content: String(m.content) };
    });

    // Track free daily prompt count
    if (!isPro && currentUser) {
      usageDB.incrementPrompt(currentUser.id).catch(() => {});
      const dayStart = getDayStart();
      setUsageData(prev => prev ? {
        ...prev,
        day_start: dayStart,
        prompts_today: (prev.day_start === dayStart ? (prev.prompts_today || 0) : 0) + 1,
      } : prev);
    }

    try {
      const SYSTEM_PROMPT = buildSystemPrompt();
      const res = await fetch("https://nahextkqnsmluuskjxps.supabase.co/functions/v1/anthropic-proxy", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Authorization": `Bearer ${SUPABASE_ANON_KEY}` },
        body: JSON.stringify({
          max_tokens: 1000,
          system: SYSTEM_PROMPT,
          messages: apiMsgs,
        }),
      });
      const data = await res.json();
      const rawReply = data.content?.map(b => b.text || "").join("") || "No response received.";
      // Remove em dashes and unnecessary vertical bars from AI responses
      const reply = rawReply
        .replace(/\s*—\s*/g, " ")       // em dash → space
        .replace(/\s*–\s*/g, " ")       // en dash → space
        .replace(/^\s*\|\s*/gm, "")     // leading vertical bars on lines
        .replace(/\s*\|\s*$/gm, "")     // trailing vertical bars on lines
        .replace(/\s*\|\s*/g, " ");     // inline vertical bars → space
      setMessages(prev => [...prev, { role: "assistant", content: reply }]);

      // ── TRACK TOKEN USAGE (Pro/Team) ────────────────────────────────────────
      if (isPro && currentUser) {
        const inputTokens = estimateTokens(msg) + estimateTokens(SYSTEM_PROMPT);
        const outputTokens = estimateTokens(reply);
        const totalTokens = inputTokens + outputTokens;
        usageDB.addTokens(currentUser.id, totalTokens).then(async () => {
          const updated = await usageDB.getUsage(currentUser.id);
          if (updated) setUsageData(updated);
        }).catch(() => {});
      }
    } catch {
      setMessages(prev => [...prev, { role: "assistant", content: "Connection error. Please try again." }]);
    } finally {
      setLoading(false);
    }
  };

  const isEmpty = messages.length === 0;

  return (
    <div style={{
      height: "var(--app-height, 100svh)", display: "flex", flexDirection: "column",
      background: isPro ? "linear-gradient(135deg, #eef3fb 0%, #e0eaf8 40%, #dde8f5 70%, #e8f0fa 100%)" : "#f8fafc",
      fontFamily: "'Inter', sans-serif", overflow: "hidden", position: "relative",
    }}>
      <style>{`
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        :root { --app-height: 100svh; }
        @keyframes bounceDot { 0%,80%,100% { transform:translateY(0); opacity:0.4; } 40% { transform:translateY(-4px); opacity:1; } }
        @keyframes msgIn { from { opacity:0; transform:translateY(8px); } to { opacity:1; transform:translateY(0); } }
        @keyframes slideIn { from { opacity:0; transform:translateX(-8px); } to { opacity:1; transform:translateX(0); } }
        @keyframes liveGlow { 0%,100% { opacity:1; box-shadow:0 0 4px #ef4444; } 50% { opacity:0.3; box-shadow:0 0 0px #ef4444; } }
        * { box-sizing:border-box; font-family: 'Inter', sans-serif; }
        textarea { resize:none; }
        textarea:focus { outline:none; }
        textarea::placeholder { color:#94a3b8; }
        .sidebar-item:hover { background:#f1f5f9 !important; color:#1e293b !important; }
        .quick-btn:hover { background:#f1f5f9 !important; border-color:#cbd5e1 !important; color:#1e293b !important; }
        .send-btn:hover { background:#374151 !important; }
        ::-webkit-scrollbar { width:4px; }
        ::-webkit-scrollbar-track { background:transparent; }
        ::-webkit-scrollbar-thumb { background:#cbd5e1; border-radius:2px; }
        .overlay { position:fixed; inset:0; background:rgba(15,23,42,0.15); z-index:25; backdrop-filter:blur(1px); }
        .hdr-email { display:inline; }
        .hdr-new-session { display:inline-flex !important; }
        .hdr-help { display:inline-flex !important; }
        @media (max-width: 680px) {
          .hdr-email { display:none !important; }
          .hdr-new-session { display:none !important; }
          .hdr-help { display:none !important; }
          .hdr-logo-sub { display:none !important; }
          .hdr-logo-text { font-size:11px !important; }
        }
        @media (max-width: 480px) {
          .hdr-token-pct { display:none !important; }
        }
        .input-bar-wrap { padding-bottom: calc(8px + env(safe-area-inset-bottom)) !important; }
        @supports (height: 100dvh) { .app-root { height: 100dvh !important; } }
        @media (max-width: 768px) {
          .main-scroll-area { overscroll-behavior: contain; -webkit-overflow-scrolling: touch; }
        }
        @media (max-width: 500px) { .personalize-grid { grid-template-columns: 1fr !important; } }
      `}</style>

      {showPaywall && <ProPaywall onClose={() => setShowPaywall(false)} userId={currentUser?.id} />}
      {promptInputModal && <PromptInputModal config={promptInputModal.config} prefilled={promptInputModal.prefilled} onSubmit={(msg) => sendMessage(msg)} onClose={() => setPromptInputModal(null)} />}
      {showAffiliate && <AffiliateDashboard isPro={isPro} userId={currentUser?.id} onClose={() => setShowAffiliate(false)} />}
      {showSupport && <SupportPage onClose={() => setShowSupport(false)} userEmail={currentUser?.email} />}
      {showOwnerAdmin && currentUser?.role === "owner" && (
        <OwnerAccessPanel
          currentUser={currentUser}
          onClose={() => setShowOwnerAdmin(false)}
          onAccessUpdated={() => {
            const session = supabase.auth.getSession();
            if (!session?.access_token || !currentUser?.id) return;
            supabase.db.getUserTier(currentUser.id, session.access_token).then((tier) => {
              setAuthTier(tier);
              setIsPro(tier === "pro" || tier === "team");
              setIsTeam(tier === "team");
            }).catch(() => {});
          }}
        />
      )}
      {showGame && <CloseOrLoseGame currentUser={currentUser} onExit={() => setShowGame(false)} isPro={isPro} />}
      {showProfitEngine && <ProfitEngine onExit={() => setShowProfitEngine(false)} isPro={isPro} onUpgrade={() => { setShowProfitEngine(false); setShowPaywall(true); }} />}
      {showLeaderboard && <MiniLeaderboard currentUser={currentUser} isPro={isPro} onClose={() => setShowLeaderboard(false)} onPlay={() => setShowGame(true)} />}
      {showSalesIQ && <SalesIQAssessment onExit={() => setShowSalesIQ(false)} isPro={isPro} currentUser={currentUser} />}
      {showUpgradePrompt && <UpgradePrompt feature={upgradeFeatureName} onClose={() => setShowUpgradePrompt(false)} onUpgrade={() => { setShowUpgradePrompt(false); setShowPaywall(true); }} />}
      {showChangelog && <ChangelogModal isLoggedIn={authTier !== "loggedout"} onClose={() => setShowChangelog(false)} />}

      {/* ── Usage Modals ── */}
      {showFreeSessionLimit && (
        <FreeSessionLimitModal
          userId={currentUser?.id}
          onUpgrade={() => { setShowFreeSessionLimit(false); setShowPaywall(true); }}
          onClose={() => setShowFreeSessionLimit(false)}
        />
      )}
      {showProTokenWarning && (
        <ProTokenWarningModal
          userId={currentUser?.id}
          tokensUsed={(usageData?.month_start === getMonthStart() ? usageData?.tokens_used_this_month : 0) || 0}
          onUpgrade={() => { setShowProTokenWarning(false); window.open(stripeLink(STRIPE_TOPUP_LINK, currentUser?.id), "_blank"); }}
          onClose={() => setShowProTokenWarning(false)}
        />
      )}
      {showProTokenLimit && (
        <ProTokenLimitModal
          userId={currentUser?.id}
          onUpgrade={() => { setShowProTokenLimit(false); window.open(stripeLink(STRIPE_TOPUP_LINK, currentUser?.id), "_blank"); }}
          onClose={() => setShowProTokenLimit(false)}
        />
      )}

      {showInstallBanner && (
        <div style={{ position: "fixed", bottom: 80, left: "50%", transform: "translateX(-50%)", zIndex: 300, width: "calc(100% - 32px)", maxWidth: 420, background: "#0f172a", borderRadius: 14, padding: "14px 16px", boxShadow: "0 8px 32px rgba(15,23,42,0.35)", display: "flex", alignItems: "center", gap: 12, animation: "msgIn 0.25s ease" }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: "#fff", fontFamily: "'Inter', sans-serif" }}>Add SalesLab to your home screen</div>
            <div style={{ fontSize: 11, color: "#64748b", fontFamily: "'Inter', sans-serif", marginTop: 2 }}>Open instantly, train anywhere</div>
          </div>
          <button onClick={handleInstallClick} style={{ padding: "7px 14px", borderRadius: 8, border: "none", background: "#3b82f6", color: "#fff", fontSize: 12, fontWeight: 700, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Install</button>
          <button onClick={() => setShowInstallBanner(false)} style={{ background: "none", border: "none", color: "#475569", fontSize: 18, cursor: "pointer", lineHeight: 1, padding: "2px 4px" }}>×</button>
        </div>
      )}

      {swUpdateReady && (
        <div style={{ position: "fixed", bottom: 24, left: "50%", transform: "translateX(-50%)", zIndex: 300, background: "#1e293b", borderRadius: 12, padding: "12px 16px", display: "flex", alignItems: "center", gap: 12, fontSize: 13, color: "#fff", fontFamily: "'Inter', sans-serif", animation: "msgIn 0.25s ease" }}>
          <span>🔄 New version available</span>
          <button onClick={handleSwUpdate} style={{ padding: "5px 12px", borderRadius: 7, border: "none", background: "#3b82f6", color: "#fff", fontSize: 12, fontWeight: 700, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Update now</button>
          <button onClick={() => setSwUpdateReady(false)} style={{ background: "none", border: "none", color: "#64748b", fontSize: 16, cursor: "pointer", padding: "0 2px" }}>×</button>
        </div>
      )}

      {sidebarOpen && <div className="overlay" onClick={() => setSidebarOpen(false)} />}

      {/* Sidebar */}
      <div style={{
        position: "fixed", top: 0, left: 0, bottom: 0, width: 260,
        transform: sidebarOpen ? "translateX(0)" : "translateX(-100%)",
        transition: "transform 0.28s cubic-bezier(0.4,0,0.2,1)",
        background: "#ffffff", borderRight: "1px solid #e2e8f0",
        display: "flex", flexDirection: "column", zIndex: 30,
        boxShadow: sidebarOpen ? "4px 0 32px rgba(0,0,0,0.08)" : "none",
      }}>
        <div style={{ padding: "16px 18px", borderBottom: "1px solid #f1f5f9", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <span style={{ fontSize: 11, fontWeight: 700, color: "#4b5563", letterSpacing: "0.08em" }}>{isPro ? "Pro Menu" : "MENU"}</span>
          <button onClick={() => setSidebarOpen(false)} style={{ background: "none", border: "none", cursor: "pointer", color: "#94a3b8", fontSize: 18, lineHeight: 1, padding: "2px 4px" }}>×</button>
        </div>

        <div style={{ overflowY: "auto", flex: 1, padding: "10px 0" }}>
          {SIDEBAR.map(sys => {
            const isLocked = !isPro && sys.proOnly;
            const isActive = activeSection === sys.id;
            const isGame = sys.isGame;
            const isProfitEngine = sys.isProfitEngine;
            const isSalesIQ = sys.isSalesIQ;
            return (
              <div key={sys.id} style={{ marginBottom: 2 }}>
                <button onClick={() => {
                  if (isLocked) { setShowPaywall(true); setSidebarOpen(false); return; }
                  if (isGame) { setShowGame(true); setSidebarOpen(false); return; }
                  if (isProfitEngine) { setShowProfitEngine(true); setSidebarOpen(false); return; }
                  if (isSalesIQ) { setShowSalesIQ(true); setSidebarOpen(false); return; }
                  setActiveSection(sys.id);
                  setMessages([]);
                  setSidebarOpen(false);
                }} style={{
                  width: "100%", padding: isGame ? "10px 18px" : "9px 18px",
                  background: isGame ? "linear-gradient(135deg,#1a0808,#0f172a)" : isActive ? "#f8fafc" : "transparent",
                  border: "none",
                  borderLeft: isGame ? "3px solid #ef4444" : isActive ? "3px solid #1e293b" : "3px solid transparent",
                  color: isLocked ? "#cbd5e1" : isGame ? "#fca5a5" : isActive ? "#1e293b" : "#64748b",
                  cursor: "pointer", textAlign: "left",
                  fontFamily: "'Inter', sans-serif", fontSize: 11, letterSpacing: "0.06em", fontWeight: 600,
                  display: "flex", alignItems: "center", gap: 10,
                }}>
                  {isGame ? (
                    <>
                      <span style={{ fontSize: 13 }}>⚔️</span>
                      <div style={{ flex: 1 }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                          <span style={{ color: "#fca5a5", fontWeight: 700 }}>CLOSE OR LOSE</span>
                          {/* Pulsing live dot */}
                          <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#ef4444", display: "inline-block", animation: "liveGlow 1.5s ease-in-out infinite" }} />
                          <span style={{ fontSize: 9, color: "#ef4444", fontWeight: 700 }}>LIVE</span>
                        </div>
                        {isLocked
                          ? <div style={{ fontSize: 9, color: "#475569", marginTop: 1 }}>Pro feature — upgrade to play</div>
                          : <div style={{ fontSize: 9, color: "#64748b", marginTop: 1 }}>Resets {getNextSundayReset()}</div>
                        }
                      </div>
                      {isLocked
                        ? <span style={{ fontSize: 9, color: "#f59e0b", background: "#fffbeb", border: "1px solid #fde68a", borderRadius: 3, padding: "1px 5px", fontWeight: 700, flexShrink: 0 }}>PRO</span>
                        : <span style={{ fontSize: 9, color: "#ef4444", background: "#1a0808", border: "1px solid #ef444430", borderRadius: 3, padding: "1px 5px", fontWeight: 700, flexShrink: 0 }}>PLAY</span>
                      }
                    </>
                  ) : (
                    <>
                      <span style={{ fontSize: 10, fontWeight: 700, color: isLocked ? "#e2e8f0" : isActive ? "#4b5563" : "#94a3b8" }}>{sys.icon}</span>
                      <span style={{ flex: 1 }}>{sys.label.toUpperCase()}</span>
                      {isLocked && <span style={{ fontSize: 9, color: "#f59e0b", background: "#fffbeb", border: "1px solid #fde68a", borderRadius: 3, padding: "1px 5px", fontWeight: 700 }}>PRO</span>}
                    </>
                  )}
                </button>
                {isGame && (
                  <button onClick={() => { setShowLeaderboard(true); setSidebarOpen(false); }} style={{ width: "100%", padding: "5px 18px 8px 41px", background: "linear-gradient(135deg,#1a0808,#0f172a)", border: "none", borderLeft: "3px solid #ef4444", borderTop: "1px solid #1e293b20", color: "#475569", fontSize: 10, fontWeight: 600, cursor: "pointer", textAlign: "left", fontFamily: "'Inter', sans-serif", display: "flex", alignItems: "center", gap: 5 }}>
                    🏆 <span style={{ color: "#64748b" }}>View Leaderboard →</span>
                  </button>
                )}
              </div>
            );
          })}

          {!isPro && (
            <div style={{ margin: "16px 12px 8px", padding: "14px", borderRadius: 10, background: "#f8fafc", border: "1px solid #e2e8f0" }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: "#1e293b", marginBottom: 4 }}>⚡ {BRAND_CONFIG.appName} (Pro)</div>
              <div style={{ fontSize: 11, color: "#64748b", lineHeight: 1.5, marginBottom: 10 }}>Roleplays, deal coaching, close scores & more.</div>
              <button onClick={() => setShowPaywall(true)} style={{ width: "100%", padding: "8px", borderRadius: 7, background: "#1e293b", border: "none", color: "#fff", fontSize: 11, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Upgrade — $29/mo</button>
            </div>
          )}
        </div>

        <div style={{ padding: "10px 12px", borderTop: "1px solid #f1f5f9" }}>
          <a href={isTeam ? "/saleslab-team-manual.pdf" : isPro ? "/saleslab-pro-manual.pdf" : "/saleslab-free-manual.pdf"} target="_blank" rel="noopener noreferrer" style={{ textDecoration: "none", display: "block", marginBottom: 8 }}>
            <div style={{ width: "100%", padding: "10px 14px", borderRadius: 9, background: "#f8fafc", border: "1px solid #e2e8f0", display: "flex", alignItems: "center", gap: 9, cursor: "pointer" }}>
              <span style={{ fontSize: 15 }}>📖</span>
              <div><div style={{ fontSize: 12, fontWeight: 600, color: "#1e293b" }}>Training Manual</div><div style={{ fontSize: 10, color: "#94a3b8", marginTop: 1 }}>Download your {isTeam ? "Team" : isPro ? "Pro" : "Free"} guide (PDF)</div></div>
            </div>
          </a>
          <button onClick={() => { setShowAffiliate(true); setSidebarOpen(false); }} style={{ width: "100%", padding: "10px 14px", borderRadius: 9, background: "#f8fafc", border: "1px solid #e2e8f0", color: "#1e293b", fontSize: 12, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif", display: "flex", alignItems: "center", gap: 9, marginBottom: 8 }}>
            <span style={{ fontSize: 15 }}>🤝</span>
            <div style={{ textAlign: "left" }}><div style={{ fontSize: 12, fontWeight: 600, color: "#1e293b" }}>Affiliate Program</div><div style={{ fontSize: 10, color: "#94a3b8", marginTop: 1 }}>Earn 30% recurring commission</div></div>
          </button>
          <button onClick={() => { setShowSupport(true); setSidebarOpen(false); }} style={{ width: "100%", padding: "10px 14px", borderRadius: 9, background: "#f8fafc", border: "1px solid #e2e8f0", color: "#1e293b", fontSize: 12, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif", display: "flex", alignItems: "center", gap: 9 }}>
            <span style={{ fontSize: 15 }}>🎧</span>
            <div style={{ textAlign: "left" }}><div style={{ fontSize: 12, fontWeight: 600, color: "#1e293b" }}>Help & Support</div><div style={{ fontSize: 10, color: "#94a3b8", marginTop: 1 }}>Contact us · FAQ</div></div>
          </button>
        </div>

        <div style={{ padding: "12px 18px", borderTop: "1px solid #f1f5f9", fontSize: 9, color: "#cbd5e1", letterSpacing: "0.15em" }}>
          SALESLAB AI
        </div>
      </div>

      {/* Header */}
      <div style={{
        display: "flex", alignItems: "center", gap: 10,
        paddingLeft: 14, paddingRight: 14,
        paddingTop: "env(safe-area-inset-top)",
        height: "calc(48px + env(safe-area-inset-top))",
        background: isPro ? "#dde6f2" : "#ffffff",
        borderBottom: isPro ? "1px solid rgba(59,130,246,0.18)" : "1px solid #e2e8f0",
        position: "relative", zIndex: 20, flexShrink: 0, overflow: "hidden",
      }}>
        <button onClick={() => setSidebarOpen(s => !s)} style={{ background: "transparent", border: "1px solid #e2e8f0", color: "#64748b", fontSize: 14, cursor: "pointer", padding: "5px 9px", lineHeight: 1, borderRadius: 6, flexShrink: 0 }}>☰</button>

        <div style={{ display: "flex", alignItems: "center", gap: 8, flexShrink: 0 }}>
          <img src={BRAND_CONFIG.logoPath} alt={BRAND_CONFIG.appName} style={{ width: 28, height: 28, borderRadius: 7, objectFit: "cover", flexShrink: 0 }} />
          <div>
            <div className="hdr-logo-text" style={{ fontSize: 12, fontWeight: 700, color: "#0f172a", letterSpacing: "0.04em", lineHeight: 1.1, whiteSpace: "nowrap" }}>
              SALESLAB AI
            </div>
            <div className="hdr-logo-sub" style={{ color: "#94a3b8", fontSize: 8, letterSpacing: "0.18em", whiteSpace: "nowrap" }}>TRAIN · TEST · CLOSE</div>
          </div>
        </div>


        <div style={{ marginLeft: "auto", display: "flex", gap: 8, alignItems: "center" }}>
          {currentUser?.role === "owner" && <button onClick={() => setShowOwnerAdmin(true)} style={{ background: "#eff6ff", border: "1px solid #bfdbfe", color: "#1d4ed8", borderRadius: 7, padding: "6px 12px", fontSize: 11, fontWeight: 700, cursor: "pointer", letterSpacing: "0.04em" }}>Admin</button>}
          {!isPro && <button onClick={() => setShowPaywall(true)} style={{ background: "#1e293b", border: "none", color: "#fff", borderRadius: 7, padding: "6px 14px", fontSize: 11, fontWeight: 600, cursor: "pointer", letterSpacing: "0.04em" }}>⚡ Upgrade to (Pro)</button>}
          {isPro && (() => {
            const tokensUsed = (usageData?.month_start === getMonthStart() ? usageData?.tokens_used_this_month : 0) || 0;
            const pct = Math.max(0, Math.round((1 - tokensUsed / PRO_MAX_TOKENS_PER_MONTH) * 100));
            const isLow = pct <= 20;
            return (
              <div className="hdr-token-pct" style={{ display: "flex", alignItems: "center", gap: 6, padding: "4px 10px", borderRadius: 8, background: isLow ? "rgba(239,68,68,0.07)" : "rgba(241,245,249,0.8)", border: `1px solid ${isLow ? "rgba(239,68,68,0.25)" : "#e2e8f0"}`, transition: "all 0.3s" }}>
                <span style={{ fontSize: 10, fontWeight: 700, color: isLow ? "#dc2626" : "#64748b", fontFamily: "'Inter', sans-serif", letterSpacing: "0.04em", whiteSpace: "nowrap" }}>
                  {isLow ? "⚠ " : ""}{pct}% tokens
                </span>
                {isLow && (
                  <a href={stripeLink(STRIPE_TOPUP_LINK, currentUser?.id)} target="_blank" rel="noreferrer" style={{ fontSize: 10, fontWeight: 700, color: "#fff", background: "#dc2626", borderRadius: 5, padding: "2px 7px", textDecoration: "none", fontFamily: "'Inter', sans-serif", letterSpacing: "0.04em", whiteSpace: "nowrap" }}>
                    Top up
                  </a>
                )}
              </div>
            );
          })()}
          {isPro && <SubscriberBadge tier={isTeam ? "team" : "pro"} />}
          {authTier === "team" && <button onClick={() => setIsTeam(true)} style={{ background: "transparent", border: "1px solid #3b82f6", color: "#3b82f6", borderRadius: 6, padding: "5px 14px", fontSize: 10, fontWeight: 600, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>👥 Team Dashboard</button>}
          {currentUser?.email && <span className="hdr-email" style={{ fontSize: 10, color: "#94a3b8", maxWidth: 140, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{currentUser.email}</span>}
          <button className="hdr-help" onClick={() => setShowSupport(true)} style={{ background: "transparent", border: "1px solid #e2e8f0", color: "#64748b", borderRadius: 6, padding: "5px 10px", fontSize: 13, cursor: "pointer", fontWeight: 600, lineHeight: 1 }} title="Help">?</button>
          {messages.length > 0 && <button className="hdr-new-session" onClick={() => { setMessages([]); setSessionObjCount(0); }} style={{ background: "transparent", border: "1px solid #e2e8f0", color: "#64748b", borderRadius: 6, padding: "5px 14px", fontSize: 10, cursor: "pointer" }}>NEW SESSION</button>}
          <button onClick={handleSignOut} style={{ background: "transparent", border: "1px solid #e2e8f0", color: "#94a3b8", borderRadius: 6, padding: "5px 12px", fontSize: 10, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>Sign out</button>
        </div>
      </div>

      {/* Main */}
      <div style={{ flex: 1, display: "flex", overflow: "hidden", position: "relative", zIndex: 10 }}>
        <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>

          <div style={{ flex: 1, overflowY: "auto", padding: "28px 32px 16px" }}>
            {activeSection !== null ? (
              // ── Section Page ──
              (() => {
                const page = SECTION_PAGES[activeSection];
                if (!page) return null;
                return (
                  <div style={{ maxWidth: 720, margin: "0 auto" }}>
                    <button onClick={() => setActiveSection(null)} style={{ background: "none", border: "none", color: "#64748b", fontSize: 12, cursor: "pointer", fontFamily: "'Inter', sans-serif", padding: "0 0 16px 0", display: "flex", alignItems: "center", gap: 6 }}>
                      ← Back to Chat
                    </button>
                    <div style={{ marginBottom: 20 }}>
                      <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 8 }}>{page.icon} / {page.label.toUpperCase()}</div>
                      <div style={{ fontSize: 22, fontWeight: 700, color: "#0f172a", letterSpacing: "-0.02em", marginBottom: 8 }}>{page.label}</div>
                      <div style={{ color: "#64748b", fontSize: 13.5, lineHeight: 1.65 }}>{page.desc}</div>
                    </div>

                    {/* ── Personalization Dropdowns ── */}
                    <div style={{ marginBottom: 24, padding: "16px 20px", borderRadius: 14, background: "#f8fafc", border: "1px solid #e2e8f0" }}>
                      <div style={{ fontSize: 10, fontWeight: 700, color: "#94a3b8", letterSpacing: "0.15em", marginBottom: 12 }}>PERSONALIZE YOUR PROMPTS</div>
                      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }} className="personalize-grid">
                        <div>
                          <div style={{ fontSize: 11, fontWeight: 600, color: "#475569", marginBottom: 5 }}>Industry</div>
                          <select value={sectionIndustry || ""} onChange={e => setSectionIndustry(e.target.value || null)}
                            style={{ width: "100%", padding: "7px 28px 7px 10px", borderRadius: 8, border: sectionIndustry ? "1.5px solid #3b82f6" : "1px solid #e2e8f0", background: "#ffffff", color: sectionIndustry ? "#0f172a" : "#475569", fontSize: 12, fontFamily: "'Inter', sans-serif", cursor: "pointer", appearance: "none", fontWeight: sectionIndustry ? 600 : 400, backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%2394a3b8' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E")`, backgroundRepeat: "no-repeat", backgroundPosition: "right 10px center" }}>
                            <option value="">— Select —</option>
                            {["Home Improvement", "Real Estate & Property", "Automotive", "Retail High-Ticket", "Business & Technology", "Financial", "Other"].map(group => (
                              <optgroup key={group} label={group}>
                                {SECTION_INDUSTRIES.filter(i => i.group === group).map(i => (
                                  <option key={i.id} value={i.id}>{i.label}</option>
                                ))}
                              </optgroup>
                            ))}
                          </select>
                        </div>
                        <div>
                          <div style={{ fontSize: 11, fontWeight: 600, color: "#475569", marginBottom: 5 }}>Role</div>
                          <select value={sectionRole || ""} onChange={e => setSectionRole(e.target.value || null)}
                            style={{ width: "100%", padding: "7px 28px 7px 10px", borderRadius: 8, border: sectionRole ? "1.5px solid #3b82f6" : "1px solid #e2e8f0", background: "#ffffff", color: sectionRole ? "#0f172a" : "#475569", fontSize: 12, fontFamily: "'Inter', sans-serif", cursor: "pointer", appearance: "none", fontWeight: sectionRole ? 600 : 400, backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%2394a3b8' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E")`, backgroundRepeat: "no-repeat", backgroundPosition: "right 10px center" }}>
                            <option value="">— Select —</option>
                            {SECTION_ROLES.map(r => <option key={r.id} value={r.id}>{r.label}</option>)}
                          </select>
                        </div>
                        <div>
                          <div style={{ fontSize: 11, fontWeight: 600, color: "#475569", marginBottom: 5 }}>Environment</div>
                          <select value={sectionEnv || ""} onChange={e => setSectionEnv(e.target.value || null)}
                            style={{ width: "100%", padding: "7px 28px 7px 10px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#ffffff", color: sectionEnv ? "#0f172a" : "#475569", fontWeight: sectionEnv ? 600 : 400, fontSize: 12, fontFamily: "'Inter', sans-serif", cursor: "pointer", appearance: "none", backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='${sectionEnv ? "%23ffffff" : "%2394a3b8"}' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E")`, backgroundRepeat: "no-repeat", backgroundPosition: "right 10px center" }}>
                            <option value="">— Select —</option>
                            {SECTION_ENVS.map(e => <option key={e.id} value={e.id}>{e.label}</option>)}
                          </select>
                        </div>
                      </div>
                      {(sectionIndustry || sectionRole || sectionEnv) && (
                        <div style={{ marginTop: 10, fontSize: 11, color: "#3b82f6", fontWeight: 600 }}>
                          ✓ Prompts tailored for {[SECTION_INDUSTRIES.find(x => x.id === sectionIndustry)?.label, SECTION_ROLES.find(x => x.id === sectionRole)?.label, SECTION_ENVS.find(x => x.id === sectionEnv)?.label].filter(Boolean).join(" · ")}
                        </div>
                      )}
                    </div>

                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                      {page.subsections.map((sub, i) => (
                        <button key={i} onClick={() => {
                          setActiveSection(null);
                          sendMessage(personalizeSectionPrompt(sub.prompt, sectionIndustry, sectionRole, sectionEnv));
                        }} style={{
                          padding: "18px 20px", borderRadius: 12, textAlign: "left",
                          background: "#ffffff", border: "1px solid #e2e8f0",
                          cursor: "pointer", fontFamily: "'Inter', sans-serif",
                          boxShadow: "0 1px 3px rgba(0,0,0,0.04)",
                          transition: "border-color 0.15s, box-shadow 0.15s",
                        }}
                          onMouseEnter={e => { e.currentTarget.style.borderColor = "#1e293b"; e.currentTarget.style.boxShadow = "0 4px 12px rgba(0,0,0,0.08)"; }}
                          onMouseLeave={e => { e.currentTarget.style.borderColor = "#e2e8f0"; e.currentTarget.style.boxShadow = "0 1px 3px rgba(0,0,0,0.04)"; }}
                        >
                          <div style={{ fontSize: 13, fontWeight: 700, color: "#0f172a", marginBottom: 6 }}>{sub.label}</div>
                          <div style={{ fontSize: 12, color: "#64748b", lineHeight: 1.6 }}>{sub.desc}</div>
                          {(sectionIndustry || sectionRole || sectionEnv) && (
                            <div style={{ marginTop: 8, fontSize: 10, color: "#3b82f6", fontWeight: 600 }}>
                              Tailored for {[SECTION_INDUSTRIES.find(x => x.id === sectionIndustry)?.label, SECTION_ROLES.find(x => x.id === sectionRole)?.label, SECTION_ENVS.find(x => x.id === sectionEnv)?.label].filter(Boolean).join(" · ")}
                            </div>
                          )}
                          <div style={{ marginTop: 8, fontSize: 11, fontWeight: 600, color: "#3b82f6" }}>Start →</div>
                        </button>
                      ))}
                    </div>
                  </div>
                );
              })()
            ) : isEmpty ? (
              <div style={{ maxWidth: 680, margin: "0 auto" }}>
                <div style={{ marginBottom: 32, paddingTop: 8 }}>
                  <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "4px 12px", borderRadius: 20, background: isPro ? "#1e293b" : "#f1f5f9", border: `1px solid ${isPro ? "#334155" : "#e2e8f0"}`, marginBottom: 18 }}>
                    <div style={{ width: 5, height: 5, borderRadius: "50%", background: isPro ? "#86efac" : "#94a3b8" }} />
                    <span style={{ fontSize: 10, color: isPro ? "#d1fae5" : "#64748b", fontWeight: 600, letterSpacing: "0.1em" }}>{isPro ? "Pro · System Ready" : "FREE PLAN"}</span>
                  </div>
                  <div style={{ fontSize: 26, fontWeight: 700, color: "#0f172a", letterSpacing: "-0.02em", marginBottom: 8, lineHeight: 1.2 }}>{isPro ? BRAND_CONFIG.appName + " (Pro)" : BRAND_CONFIG.appName}</div>
                  <div style={{ color: "#64748b", fontSize: 13, lineHeight: 1.65 }}>{isPro ? "Elite training & coaching for in-home sales reps and SaaS/AE closers." : "Practical sales coaching for in-home reps and SaaS closers. Upgrade to (Pro) for roleplays, deal coaching & more."}</div>
                </div>

                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12, marginBottom: 24 }}>
                  {(isPro ? [
                    { code: "01", title: "Training", desc: "Roleplay, drills, full deal simulations & frameworks" },
                    { code: "02", title: "Coaching", desc: "Real-time call coaching, deal analysis & competitive prep" },
                    { code: "03", title: "Performance", desc: "Close Intelligence Scores, reports & practice plans" },
                  ] : [
                    { code: "01", title: "Objections", desc: "ACRC framework for any objection, any situation" },
                    { code: "02", title: "Scripts", desc: "Instant rewrites with best & alternate versions" },
                    { code: "03", title: "Discovery", desc: "6–10 targeted questions for any sales situation" },
                  ]).map((s, i) => (
                    <div key={i} style={{ padding: "16px", borderRadius: 10, background: "#ffffff", border: "1px solid #e2e8f0", boxShadow: "0 1px 3px rgba(0,0,0,0.04)" }}>
                      <div style={{ fontSize: 10, fontWeight: 700, color: "#4b5563", letterSpacing: "0.1em", marginBottom: 6 }}>{s.code} / {s.title.toUpperCase()}</div>
                      <div style={{ color: "#64748b", fontSize: 11.5, lineHeight: 1.6 }}>{s.desc}</div>
                    </div>
                  ))}
                </div>

                {!isPro && (
                  <div style={{ padding: "16px 20px", borderRadius: 12, marginBottom: 24, background: "#EFF6FF", border: "0.5px solid #BFDBFE", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 600, color: "#1E3A8A", marginBottom: 3 }}>⚡ Unlock {BRAND_CONFIG.appName} (Pro)</div>
                      <div style={{ fontSize: 11.5, color: "#1D4ED8", lineHeight: 1.5 }}>Roleplays, deal coaching, transcript analysis, close scores & more.</div>
                    </div>
                    <div style={{ display: "flex", flexDirection: "column", gap: 6, flexShrink: 0 }}>
                      <button onClick={() => setShowPaywall(true)} style={{ padding: "8px 14px", borderRadius: 8, background: "#1D4ED8", border: "none", color: "#fff", fontSize: 12, fontWeight: 700, cursor: "pointer", whiteSpace: "nowrap" }}>Pro $29 →</button>
                      <button onClick={() => setShowPaywall(true)} style={{ padding: "8px 14px", borderRadius: 8, background: "transparent", border: "0.5px solid #BFDBFE", color: "#1D4ED8", fontSize: 11, fontWeight: 600, cursor: "pointer", whiteSpace: "nowrap" }}>Team $199/mo →</button>
                    </div>
                  </div>
                )}

                <HomeLeaderboardTeaser onViewLeaderboard={() => setShowLeaderboard(true)} />

                <DailyTipCard />

                <SalesIQDashboardCard
                  onTakeTest={() => setShowSalesIQ(true)}
                  isPro={isPro}
                  onUpgrade={() => setShowPaywall(true)}
                />

                <div>
                  <div style={{ fontSize: 10, color: "#94a3b8", letterSpacing: "0.2em", marginBottom: 12, fontWeight: 600 }}>QUICK START</div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                    <button className="quick-btn" onClick={() => setShowSalesIQ(true)} style={{ padding: "10px 14px", borderRadius: 8, textAlign: "left", background: "#EFF6FF", border: "1px solid #BFDBFE", color: "#1D4ED8", fontSize: 12.5, cursor: "pointer", fontFamily: "'Inter', sans-serif", fontWeight: 600 }}>⚡ Sales IQ Test</button>
                    {QUICK_PROMPTS.map((q, i) => (
                      <button key={i} className="quick-btn" onClick={() => sendMessage(q.prompt)} style={{ padding: "10px 14px", borderRadius: 8, textAlign: "left", background: "#ffffff", border: "1px solid #e2e8f0", color: "#475569", fontSize: 12.5, cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>{q.label}</button>
                    ))}
                  </div>
                </div>
              </div>
            ) : (
              <div style={{ maxWidth: 720, margin: "0 auto" }}>
                {messages.map((msg, i) => <Message key={i} msg={msg} />)}
                {loading && (
                  <div style={{ display: "flex", alignItems: "flex-start", gap: 10, marginBottom: 16 }}>
                    <div style={{ width: 44, height: 30, borderRadius: 6, flexShrink: 0, background: "#f9fafb", border: "1.5px solid #d1d5db", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10, color: "#4b5563", fontWeight: 700, marginTop: 2 }}>Coach</div>
                    <div style={{ padding: "10px 16px", background: "#ffffff", border: "1px solid #e2e8f0", borderRadius: "3px 12px 12px 12px" }}><TypingDots /></div>
                  </div>
                )}
                <div ref={bottomRef} />
              </div>
            )}
          </div>

          {/* Input */}
          <div className="input-bar-wrap" style={{ padding: "10px 32px 8px", borderTop: "1px solid #e2e8f0", background: "#ffffff" }}>
            <div style={{ maxWidth: 720, margin: "0 auto", display: "flex", alignItems: "flex-end", gap: 10, background: "#f8fafc", border: "1.5px solid #e2e8f0", borderRadius: 12, padding: "10px 12px" }}>
              <textarea
                ref={textareaRef}
                value={input}
                onChange={e => { setInput(e.target.value); e.target.style.height = "auto"; e.target.style.height = Math.min(e.target.scrollHeight, 150) + "px"; }}
                onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendMessage(); } }}
                onFocus={e => e.target.parentNode.style.borderColor = "#4b5563"}
                onBlur={e => e.target.parentNode.style.borderColor = "#e2e8f0"}
                placeholder={isPro ? "Type a prompt, command, or select from the menu..." : "Try: ACRC: your price is too high  |  SCRIPT: your message  |  DISCOVERY: your product"}
                rows={1}
                style={{ flex: 1, background: "transparent", border: "none", color: "#1e293b", fontSize: 13.5, lineHeight: 1.6, fontFamily: "'Inter', sans-serif", maxHeight: 150, overflow: "auto" }}
              />
              <button className="send-btn" onClick={() => sendMessage()} disabled={!input.trim() || loading} style={{ width: 34, height: 34, borderRadius: 8, flexShrink: 0, background: input.trim() && !loading ? "#1e293b" : "#e2e8f0", border: "none", color: input.trim() && !loading ? "#fff" : "#94a3b8", fontSize: 16, cursor: input.trim() && !loading ? "pointer" : "not-allowed", display: "flex", alignItems: "center", justifyContent: "center" }}>↑</button>
            </div>
            <div style={{ textAlign: "center", marginTop: 8, display: "flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
              <span style={{ color: "#cbd5e1", fontSize: 10, letterSpacing: "0.15em" }}>{BRAND_CONFIG.appNameShort} {isPro ? "Pro" : "Free"} · {BRAND_CONFIG.tagline}</span>
              <button onClick={() => setShowChangelog(true)} style={{ background: "none", border: "1px solid #e2e8f0", borderRadius: 4, padding: "1px 7px", fontSize: 9, color: "#94a3b8", cursor: "pointer", fontFamily: "'Inter', sans-serif", letterSpacing: "0.05em", fontWeight: 600 }} title="View changelog">v3.6</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
