/* global React, Icon */

const SETTINGS_SECTIONS = [
  { id: "profile", label: "Profile", icon: "userx" },
  { id: "workspace", label: "Workspace", icon: "gear" },
  { id: "team", label: "Team", icon: "users" },
  { id: "salesStudio", label: "Sales Studio", icon: "book" },
  { id: "intelligence", label: "Intelligence", icon: "sparkles" },
  { id: "headless", label: "Headless", icon: "bolt" },
  { id: "currency", label: "Currency", icon: "scale" },
  { id: "importExport", label: "Import/Export", icon: "route" },
  { id: "notifications", label: "Notifications", icon: "bell" },
  { id: "security", label: "Security", icon: "shield" },
];

const PHONE_COUNTRIES = [
  { code: "FR", dial: "+33", flag: "🇫🇷" },
  { code: "TN", dial: "+216", flag: "🇹🇳" },
  { code: "US", dial: "+1",  flag: "🇺🇸" },
  { code: "GB", dial: "+44", flag: "🇬🇧" },
  { code: "DE", dial: "+49", flag: "🇩🇪" },
];

const CURRENCIES = [
  { code: "EUR", symbol: "€", label: "Euro (€)" },
  { code: "USD", symbol: "$", label: "US Dollar ($)" },
  { code: "GBP", symbol: "£", label: "British Pound (£)" },
  { code: "TND", symbol: "د.ت", label: "Tunisian Dinar (د.ت)" },
];

const SETTINGS_INTEGRATIONS = [
  { id: "hubspot", name: "HubSpot", status: "Connected", tone: "good", detail: "Deals, contacts, companies, activities", lastSync: "7 min ago" },
  { id: "gmail", name: "Gmail", status: "Connected", tone: "good", detail: "Email metadata and thread matching", lastSync: "12 min ago" },
  { id: "calendar", name: "Google Calendar", status: "Connected", tone: "good", detail: "Meetings, attendees, next steps", lastSync: "18 min ago" },
  { id: "slack", name: "Slack", status: "Needs review", tone: "amber", detail: "Rep coaching drafts and manager nudges", lastSync: "Permission expired" },
  { id: "whatsapp", name: "WhatsApp", status: "Optional", tone: "muted", detail: "Relationship channel hints only", lastSync: "Not connected" },
];

const SETTINGS_ROLES = [
  { role: "Admin", count: 1, permissions: "Billing, security, workspace policy" },
  { role: "Manager", count: 2, permissions: "Forecast review, coaching, team analytics" },
  { role: "AE", count: 8, permissions: "Own deals, actions, buyer proof" },
  { role: "RevOps", count: 1, permissions: "Signals, CRM mapping, model calibration" },
];

const HEADLESS_USE_CASES = [
  { id: "preMeetingIntel",    icon: "book",  name: "Pre-meeting intel",     desc: "Brief delivered before each scheduled buyer meeting — buyer history, last proof, what to listen for.", timing: { label: "Lead time", unit: "min before" } },
  { id: "postMeetingDebrief", icon: "note",  name: "Post-meeting debrief",  desc: "Capture proof, next steps, and stakeholder shifts after the call. Owner-tagged.",                 timing: { label: "Delay",     unit: "min after"  } },
  { id: "crmUpdate",          icon: "route", name: "CRM update",            desc: "Write back amount, stage, next step, and contact roles to HubSpot from confirmed buyer signals.", timing: null },
  { id: "forecastRisk",       icon: "target",name: "Forecast risk alert",   desc: "Fires when commit dollars lose buyer-backed support mid-quarter.",                                timing: null },
  { id: "buyerProofGap",      icon: "flag",  name: "Buyer-proof gap",       desc: "Nudge the AE when a deal has no buyer-side acceptance after the stale-day threshold.",            timing: null },
  { id: "coachingPrompt",     icon: "chat",  name: "Coaching prompt",       desc: "Pre-built challenge question pushed to the manager before forecast review.",                      timing: null },
];

const HEADLESS_CHANNELS = [
  { value: "slack-dm",       label: "Slack DM" },
  { value: "slack-manager",  label: "Slack — Managers" },
  { value: "slack-aes",      label: "Slack — AEs" },
  { value: "email-ae",       label: "Email — AE owner" },
  { value: "email-manager",  label: "Email — Manager" },
  { value: "webhook",        label: "Custom webhook" },
  { value: "crm-direct",     label: "CRM (HubSpot)" },
  { value: "whatsapp",       label: "WhatsApp DM" },
];

const SALES_STUDIO_PLAYS = [
  { id: "stage-stall", name: "Stage stall rescue", trigger: "No buyer movement after stage advance", owner: "AE", tone: "warn" },
  { id: "exec-thread", name: "Executive thread creation", trigger: "Champion active, EB missing", owner: "AE + Manager", tone: "amber" },
  { id: "forecast-challenge", name: "Forecast challenge", trigger: "Commit without buyer-owned next step", owner: "Manager", tone: "warn" },
  { id: "post-demo-proof", name: "Post-demo proof capture", trigger: "Demo completed, no mutual action", owner: "AE", tone: "good" },
];

const NUDGE_SETTINGS_DEFAULTS = {
  profile: {
    name: "Ridha Mansour",
    email: "ridha@addvocate.ai",
    title: "Founder / AE",
    timezone: "Europe/Paris",
    phone: "(076) 445-4024",
    phoneCountry: "FR",
    annualGoal: 600000,
  },
  currency: {
    primary: "EUR",
    symbolPosition: "prefix",
    decimalPlaces: 0,
  },
  workspace: {
    name: "Nudge",
    defaultView: "ae",
    fiscalYearStart: "January",
    forecastCadence: "Weekly",
  },
  addy: {
    autonomy: "Propose",
    tone: "Direct",
    drafts: true,
    buyerProofOnly: true,
    managerCoaching: true,
  },
  signals: {
    staleDays: 9,
    gapThreshold: 18,
    economicBuyerRequired: true,
    nextStepRequired: true,
    activityPenalty: true,
  },
  notifications: {
    forecastRisk: true,
    coaching: true,
    buyerReplies: true,
    weeklyDigest: false,
  },
  security: {
    sso: false,
    auditLog: true,
    dataRetention: "18 months",
    piiMasking: true,
  },
  headless: {
    enabled: false,
    apiKey: "ndg_live_8f7a2b4c93e1d65f0a8b7c2d4e6f1a39",
    webhookUrl: "https://hooks.addvocate.ai/nudge/events",
    defaultChannel: "email",
    quietHoursStart: "20:00",
    quietHoursEnd: "07:30",
    useCases: {
      preMeetingIntel:    { enabled: true,  channel: "slack-dm",      timing: "15" },
      postMeetingDebrief: { enabled: false, channel: "email-ae",      timing: "10" },
      crmUpdate:          { enabled: true,  channel: "crm-direct",    timing: "0"  },
      forecastRisk:       { enabled: true,  channel: "slack-manager", timing: "0"  },
      buyerProofGap:      { enabled: true,  channel: "email-ae",      timing: "0"  },
      coachingPrompt:     { enabled: false, channel: "slack-manager", timing: "0"  },
    },
  },
  salesStudio: {
    businessModel: "B2B SaaS for revenue teams. Nudge helps teams separate seller activity from buyer proof, then recommends the next action that creates real buyer movement.",
    products: "Deal Truth, buyer-proof cockpit, manager forecast recalculation, coaching queue, Addy action preview.",
    icp: "B2B sales teams with long-cycle deals, multi-stakeholder buying committees, CRM activity noise, and forecast pressure.",
    buyerRoles: "CRO, VP Sales, RevOps, Sales Manager, AE, CFO / economic buyer, champion, procurement, legal.",
    salesMotion: "Founder-led and sales-led. Discovery starts from forecast pain, buyer inactivity, missed commits, and manager inspection fatigue.",
    qualification: "A qualified opportunity must have pain, business impact, a named owner, economic buyer path, buying process, and a buyer-owned next action.",
    proofRules: "Treat buyer replies, accepted meetings, shared docs, stakeholder joins, budget validation, legal owner, and dated mutual plans as proof. Do not treat seller tasks, CRM stage, or rep confidence as proof.",
    objections: "We already have CRM hygiene; managers can inspect deals manually; reps will not use another tool; AI cannot understand our process; forecast risk is subjective.",
    forbidden: "Do not say autopilot, replace reps, fully autonomous selling, guaranteed forecast, surveillance, or activity score.",
    language: "Use plain commercial language. Be direct, specific, and evidence-led. Prefer buyer-owned proof over productivity language.",
    competitors: "CRM analytics, Gong, Clari, sales engagement tools, manual forecast inspection, spreadsheets.",
    escalation: "Escalate when commit dollars lack buyer proof, economic buyer is unknown, legal/procurement owner is missing, or rep activity masks buyer silence.",
  },
  voiceMemory: "Short, direct, buyer-proof oriented. Avoid hype. Ask for one concrete next step, owner, and date.",
};

function mergeNudgeSettings(settings = {}) {
  return {
    profile: { ...NUDGE_SETTINGS_DEFAULTS.profile, ...(settings.profile || {}) },
    workspace: { ...NUDGE_SETTINGS_DEFAULTS.workspace, ...(settings.workspace || {}) },
    currency: { ...NUDGE_SETTINGS_DEFAULTS.currency, ...(settings.currency || {}) },
    addy: { ...NUDGE_SETTINGS_DEFAULTS.addy, ...(settings.addy || {}) },
    signals: { ...NUDGE_SETTINGS_DEFAULTS.signals, ...(settings.signals || {}) },
    notifications: { ...NUDGE_SETTINGS_DEFAULTS.notifications, ...(settings.notifications || {}) },
    security: { ...NUDGE_SETTINGS_DEFAULTS.security, ...(settings.security || {}) },
    headless: { ...NUDGE_SETTINGS_DEFAULTS.headless, ...(settings.headless || {}) },
    salesStudio: { ...NUDGE_SETTINGS_DEFAULTS.salesStudio, ...(settings.salesStudio || {}) },
    voiceMemory: settings.voiceMemory ?? NUDGE_SETTINGS_DEFAULTS.voiceMemory,
  };
}

function formatCurrency(amount, currency = "EUR", symbolPosition = "prefix") {
  const c = CURRENCIES.find((x) => x.code === currency) || CURRENCIES[0];
  const compact = (() => {
    if (amount >= 1_000_000) return `${(amount / 1_000_000).toFixed(amount % 1_000_000 === 0 ? 0 : 1)}M`;
    if (amount >= 1_000) return `${Math.round(amount / 1_000)}K`;
    return String(amount);
  })();
  return symbolPosition === "suffix" ? `${compact} ${c.symbol}` : `${c.symbol} ${compact}`;
}

function SettingsToggle({ checked, onChange, label, desc }) {
  return (
    <label className="settings-toggle-row">
      <span className="settings-toggle-copy">
        <b>{label}</b>
        {desc && <em>{desc}</em>}
      </span>
      <span className={`settings-switch ${checked ? "is-on" : ""}`} aria-hidden="true">
        <span />
      </span>
      <input
        type="checkbox"
        checked={checked}
        onChange={(e) => onChange(e.target.checked)}
        aria-label={label}
      />
    </label>
  );
}

function SettingsField({ label, value, placeholder, type = "text", onChange, required, adornment }) {
  return (
    <label className="settings-field">
      <span>{label}{required && " *"}</span>
      <div className={`settings-input-shell ${adornment ? "has-adornment" : ""}`}>
        {adornment && <span className="settings-input-adornment">{adornment}</span>}
        <input
          type={type}
          value={value}
          placeholder={placeholder}
          onChange={(e) => onChange(e.target.value)}
        />
      </div>
    </label>
  );
}

function SettingsSelect({ label, value, options, onChange }) {
  return (
    <label className="settings-field">
      <span>{label}</span>
      <div className="settings-input-shell">
        <select value={value} onChange={(e) => onChange(e.target.value)}>
          {options.map((option) => (
            <option key={option.value} value={option.value}>{option.label}</option>
          ))}
        </select>
      </div>
    </label>
  );
}

function SettingsTextarea({ label, value, onChange, rows = 4 }) {
  return (
    <label className="settings-textarea-field">
      <span>{label}</span>
      <textarea rows={rows} value={value} onChange={(e) => onChange(e.target.value)} />
    </label>
  );
}

function SettingsCard({ title, subtitle, titleIcon, eyebrow, action, className, children, footer }) {
  return (
    <section className={`settings-card ${className || ""}`.trim()}>
      {(title || subtitle || action || eyebrow) && (
        <header className="settings-card-head">
          <div className="settings-card-title-block">
            {eyebrow && <span className="settings-card-eyebrow">{eyebrow}</span>}
            {title && (
              <h3>
                {titleIcon && <span className="settings-card-title-icon" aria-hidden="true">{titleIcon}</span>}
                <span>{title}</span>
              </h3>
            )}
            {subtitle && <p>{subtitle}</p>}
          </div>
          {action && <div className="settings-card-action-slot">{action}</div>}
        </header>
      )}
      <div className="settings-card-body">{children}</div>
      {footer && <div className="settings-card-footer">{footer}</div>}
    </section>
  );
}

function PhoneField({ country, number, onCountryChange, onNumberChange }) {
  const selected = PHONE_COUNTRIES.find((c) => c.code === country) || PHONE_COUNTRIES[0];
  const digits = (number || "").replace(/\D/g, "");
  return (
    <label className="settings-field settings-phone-field">
      <span>Phone Number</span>
      <div className="settings-phone-grid">
        <div className="settings-input-shell settings-phone-country">
          <span className="settings-phone-flag" aria-hidden="true">{selected.flag}</span>
          <select value={country} onChange={(e) => onCountryChange(e.target.value)} aria-label="Country code">
            {PHONE_COUNTRIES.map((c) => (
              <option key={c.code} value={c.code}>{c.flag} {c.dial}</option>
            ))}
          </select>
        </div>
        <div className="settings-input-shell">
          <input
            type="tel"
            value={number}
            placeholder="(076) 445-4024"
            onChange={(e) => onNumberChange(e.target.value)}
          />
        </div>
      </div>
      <em className="settings-phone-helper">Full number: {selected.dial} {digits}</em>
    </label>
  );
}

function SettingsModule({ settings, onSettingsChange, onSave, onReset, active: activeProp, onActiveChange }) {
  const [internalActive, setInternalActive] = React.useState("profile");
  const rawActive = activeProp ?? internalActive;
  // Resolve to a valid section id — if the caller passed an unknown value
  // (e.g. a stale 'account' from before the rename), fall back to the
  // first tab so the bar always has an active state.
  const active = SETTINGS_SECTIONS.some((s) => s.id === rawActive)
    ? rawActive
    : SETTINGS_SECTIONS[0].id;
  const setActive = onActiveChange ?? setInternalActive;
  const initial = React.useMemo(() => mergeNudgeSettings(settings), []); // eslint-disable-line react-hooks/exhaustive-deps
  const [profile, setProfile] = React.useState(initial.profile);
  const [workspace, setWorkspace] = React.useState(initial.workspace);
  const [currency, setCurrency] = React.useState(initial.currency);
  const [addy, setAddy] = React.useState(initial.addy);
  const [signals, setSignals] = React.useState(initial.signals);
  const [notifications, setNotifications] = React.useState(initial.notifications);
  const [security, setSecurity] = React.useState(initial.security);
  const [headless, setHeadless] = React.useState(initial.headless);
  const [salesStudio, setSalesStudio] = React.useState(initial.salesStudio);
  const [voiceMemory, setVoiceMemory] = React.useState(initial.voiceMemory);
  const [apiKeyRevealed, setApiKeyRevealed] = React.useState(false);

  const publishSection = React.useCallback((section, next) => {
    if (onSettingsChange) onSettingsChange({ [section]: next });
  }, [onSettingsChange]);
  const updateProfile = React.useCallback((edits) => {
    const next = { ...profile, ...edits };
    setProfile(next);
    publishSection("profile", next);
  }, [profile, publishSection]);
  const updateWorkspace = React.useCallback((edits) => {
    const next = { ...workspace, ...edits };
    setWorkspace(next);
    publishSection("workspace", next);
  }, [workspace, publishSection]);
  const updateCurrency = React.useCallback((edits) => {
    const next = { ...currency, ...edits };
    setCurrency(next);
    publishSection("currency", next);
  }, [currency, publishSection]);
  const updateAddy = React.useCallback((edits) => {
    const next = { ...addy, ...edits };
    setAddy(next);
    publishSection("addy", next);
  }, [addy, publishSection]);
  const updateSignals = React.useCallback((edits) => {
    const next = { ...signals, ...edits };
    setSignals(next);
    publishSection("signals", next);
  }, [signals, publishSection]);
  const updateNotifications = React.useCallback((edits) => {
    const next = { ...notifications, ...edits };
    setNotifications(next);
    publishSection("notifications", next);
  }, [notifications, publishSection]);
  const updateSecurity = React.useCallback((edits) => {
    const next = { ...security, ...edits };
    setSecurity(next);
    publishSection("security", next);
  }, [security, publishSection]);
  const updateHeadless = React.useCallback((edits) => {
    const next = { ...headless, ...edits };
    setHeadless(next);
    publishSection("headless", next);
  }, [headless, publishSection]);
  const regenerateApiKey = React.useCallback(() => {
    const hex = "abcdef0123456789";
    let k = "ndg_live_";
    for (let i = 0; i < 32; i++) k += hex[Math.floor(Math.random() * 16)];
    updateHeadless({ apiKey: k });
    setApiKeyRevealed(true);
  }, [updateHeadless]);
  const updateSalesStudio = React.useCallback((edits) => {
    const next = { ...salesStudio, ...edits };
    setSalesStudio(next);
    publishSection("salesStudio", next);
  }, [salesStudio, publishSection]);

  const currentSettings = React.useMemo(() => ({
    profile,
    workspace,
    currency,
    addy,
    signals,
    notifications,
    security,
    headless,
    salesStudio,
    voiceMemory,
  }), [profile, workspace, currency, addy, signals, notifications, security, headless, salesStudio, voiceMemory]);
  const profileInitial = (profile.name.trim()[0] || "R").toUpperCase();

  const resetToDefaults = () => {
    const defaults = mergeNudgeSettings();
    setProfile(defaults.profile);
    setWorkspace(defaults.workspace);
    setCurrency(defaults.currency);
    setAddy(defaults.addy);
    setSignals(defaults.signals);
    setNotifications(defaults.notifications);
    setSecurity(defaults.security);
    setHeadless(defaults.headless);
    setSalesStudio(defaults.salesStudio);
    setVoiceMemory(defaults.voiceMemory);
    if (onReset) onReset(defaults);
  };

  const renderProfile = () => (
    <div className="settings-page two-col">
      <SettingsCard
        eyebrow="You"
        title="User Profile"
        subtitle="Update your personal information and contact details"
        action={
          <button type="button" className="settings-card-action" aria-label="Sign out">
            <Icon name="arrow" size={15} />
          </button>
        }
      >
        <div className="settings-photo-row">
          <span className="settings-avatar lg" aria-hidden="true">{profileInitial}</span>
          <div className="settings-photo-copy">
            <button type="button" className="settings-secondary-btn">Change Photo</button>
            <em>JPG, PNG or GIF. Max size 2MB.</em>
          </div>
        </div>
        <SettingsField
          label="Full Name"
          required
          value={profile.name}
          onChange={(name) => updateProfile({ name })}
        />
        <SettingsField
          label="Email Address"
          type="email"
          value={profile.email}
          placeholder="ridha@addvocate.ai"
          onChange={(email) => updateProfile({ email })}
        />
        <SettingsField
          label="Job Title / Role"
          value={profile.title}
          placeholder="ACCOUNT ADMIN"
          onChange={(title) => updateProfile({ title })}
        />
        <PhoneField
          country={profile.phoneCountry}
          number={profile.phone}
          onCountryChange={(phoneCountry) => updateProfile({ phoneCountry })}
          onNumberChange={(phone) => updateProfile({ phone })}
        />
        <SettingsSelect
          label="Timezone"
          value={profile.timezone}
          onChange={(timezone) => updateProfile({ timezone })}
          options={[
            { value: "Europe/Paris", label: "(UTC+01:00) Amsterdam, Berlin, Rome, Paris" },
            { value: "Africa/Tunis", label: "(UTC+01:00) Tunis, Algiers" },
            { value: "America/New_York", label: "(UTC-05:00) New York, Toronto" },
            { value: "Europe/London", label: "(UTC+00:00) London, Lisbon" },
          ]}
        />
      </SettingsCard>

      <SettingsCard
        className="settings-side-card"
        eyebrow="Target · FY26"
        title="Yearly Sales Objective"
        titleIcon={<Icon name="target" size={16} />}
        subtitle="Set your annual sales target"
      >
        <SettingsField
          label="Annual Goal"
          type="number"
          value={profile.annualGoal}
          adornment={CURRENCIES.find((c) => c.code === currency.primary)?.symbol || "€"}
          onChange={(v) => updateProfile({ annualGoal: Number(v) || 0 })}
        />
        <div className="settings-target-callout">
          <b>{formatCurrency(profile.annualGoal, currency.primary, currency.symbolPosition)}</b>
          <em>Target for {new Date().getFullYear()}</em>
        </div>
        <button type="button" className="settings-side-cta">Update Goal</button>
      </SettingsCard>
    </div>
  );

  const renderWorkspace = () => (
    <div className="settings-page">
      <SettingsCard
        title="Workspace defaults"
        subtitle="Commercial calendar, default mode, and naming rules for team-level reporting."
      >
        <div className="settings-form-grid">
          <SettingsField label="Workspace name" value={workspace.name} onChange={(name) => updateWorkspace({ name })} />
          <SettingsSelect
            label="Default view"
            value={workspace.defaultView}
            onChange={(defaultView) => updateWorkspace({ defaultView })}
            options={[
              { value: "ae", label: "AE cockpit" },
              { value: "manager", label: "Manager forecast cockpit" },
            ]}
          />
          <SettingsSelect
            label="Fiscal year starts"
            value={workspace.fiscalYearStart}
            onChange={(fiscalYearStart) => updateWorkspace({ fiscalYearStart })}
            options={["January", "April", "July", "October"].map((m) => ({ value: m, label: m }))}
          />
          <SettingsSelect
            label="Forecast cadence"
            value={workspace.forecastCadence}
            onChange={(forecastCadence) => updateWorkspace({ forecastCadence })}
            options={["Weekly", "Bi-weekly", "Monthly"].map((m) => ({ value: m, label: m }))}
          />
        </div>
      </SettingsCard>
      <SettingsCard
        title="Health checks"
        subtitle="Recurring jobs Nudge runs on your data to surface buyer proof gaps and forecast risks."
      >
        <div className="settings-rule-list">
          <span><b>Pipeline check</b><em>Weekdays at 10:02 AM</em></span>
          <span><b>Forecast review prep</b><em>Friday, 90 minutes before meeting</em></span>
          <span><b>Manager coaching queue</b><em>Critical deals first, grouped by AE</em></span>
        </div>
      </SettingsCard>
    </div>
  );

  const renderTeam = () => (
    <div className="settings-page">
      <SettingsCard
        title="Team roles"
        subtitle="Role model for account visibility, manager coaching, and forecast controls."
        action={<button type="button" className="settings-primary-btn">Invite user</button>}
      >
        <div className="settings-role-list">
          {SETTINGS_ROLES.map((role) => (
            <article key={role.role} className="settings-role-row">
              <span className="settings-role-icon"><Icon name={
                role.role === "Admin" ? "flag" :
                role.role === "Manager" ? "trend" :
                role.role === "AE" ? "handshake" :
                role.role === "RevOps" ? "sliders" :
                "users"
              } size={14} /></span>
              <div>
                <b>{role.role}</b>
                <em>{role.permissions}</em>
              </div>
              <span>{role.count} user{role.count === 1 ? "" : "s"}</span>
              <button type="button" className="settings-secondary-btn sm">Edit</button>
            </article>
          ))}
        </div>
      </SettingsCard>
    </div>
  );

  const renderSalesStudio = () => (
    <div className="settings-page">
      <SettingsCard
        eyebrow="Context · For Addy"
        title="Business specificity"
        subtitle="Who you sell to, what you sell, and what the buying committee looks like."
      >
        <SettingsTextarea label="What the business sells" value={salesStudio.businessModel} rows={4} onChange={(businessModel) => updateSalesStudio({ businessModel })} />
        <SettingsTextarea label="Products and modules" value={salesStudio.products} rows={3} onChange={(products) => updateSalesStudio({ products })} />
        <SettingsTextarea label="Ideal customer profile" value={salesStudio.icp} rows={3} onChange={(icp) => updateSalesStudio({ icp })} />
        <SettingsTextarea label="Buyer roles and buying committee" value={salesStudio.buyerRoles} rows={3} onChange={(buyerRoles) => updateSalesStudio({ buyerRoles })} />
      </SettingsCard>
      <SettingsCard
        title="Sales motion"
        subtitle="How deals get created, qualified, advanced, and escalated."
      >
        <SettingsTextarea label="How deals are created and advanced" value={salesStudio.salesMotion} rows={4} onChange={(salesMotion) => updateSalesStudio({ salesMotion })} />
        <SettingsTextarea label="Qualification rules" value={salesStudio.qualification} rows={3} onChange={(qualification) => updateSalesStudio({ qualification })} />
        <SettingsTextarea label="Buyer-proof rules" value={salesStudio.proofRules} rows={4} onChange={(proofRules) => updateSalesStudio({ proofRules })} />
        <SettingsTextarea label="Escalation rules" value={salesStudio.escalation} rows={3} onChange={(escalation) => updateSalesStudio({ escalation })} />
      </SettingsCard>
      <SettingsCard
        title="Messaging intelligence"
        subtitle="Objections, approved language, things Addy should never say, and how to read competitors."
      >
        <SettingsTextarea label="Common objections" value={salesStudio.objections} rows={4} onChange={(objections) => updateSalesStudio({ objections })} />
        <SettingsTextarea label="Approved language" value={salesStudio.language} rows={3} onChange={(language) => updateSalesStudio({ language })} />
        <SettingsTextarea label="Forbidden language" value={salesStudio.forbidden} rows={3} onChange={(forbidden) => updateSalesStudio({ forbidden })} />
        <SettingsTextarea label="Competitive context" value={salesStudio.competitors} rows={3} onChange={(competitors) => updateSalesStudio({ competitors })} />
      </SettingsCard>
      <SettingsCard
        title="Active AI plays"
        subtitle="What Addy proposes when these triggers fire, and who's expected to act on each one."
        footer={
          <div className="settings-action-row">
            <button type="button" className="settings-secondary-btn">Import docs</button>
            <button type="button" className="settings-primary-btn">Generate AI brief</button>
          </div>
        }
      >
        <div className="settings-studio-play-list">
          {SALES_STUDIO_PLAYS.map((play) => (
            <article key={play.id} className={`settings-studio-play tone-${play.tone}`}>
              <span className="settings-studio-play-dot" aria-hidden="true" />
              <div>
                <b>{play.name}</b>
                <em>{play.trigger}</em>
              </div>
              <span>{play.owner}</span>
            </article>
          ))}
        </div>
        <div className="settings-studio-brief">
          <b>What Addy should infer</b>
          <p>When drafting, Addy should use the business context above to choose the right buyer role, name the missing proof, avoid forbidden claims, and recommend a move that matches the organization&apos;s sales motion.</p>
        </div>
      </SettingsCard>
    </div>
  );

  const renderIntelligence = () => (
    <div className="settings-page">
      <SettingsCard
        title="Addy operating policy"
        subtitle="How proactive Addy can be, what she can draft, and where manager coaching starts."
      >
        <div className="settings-inline-label">Autonomy</div>
        <div className="settings-choice-grid">
          {["Observe", "Propose", "Act with approval"].map((mode) => (
            <button
              key={mode}
              type="button"
              className={`settings-choice ${addy.autonomy === mode ? "is-active" : ""}`}
              onClick={() => updateAddy({ autonomy: mode })}
            >
              <b>{mode}</b>
              <em>{mode === "Observe" ? "No drafts unless asked" : mode === "Propose" ? "Draft and wait for approval" : "Execute approved playbooks"}</em>
            </button>
          ))}
        </div>
        <SettingsSelect
          label="Drafting tone"
          value={addy.tone}
          onChange={(tone) => updateAddy({ tone })}
          options={["Direct", "Warm", "Formal", "Founder-led"].map((m) => ({ value: m, label: m }))}
        />
      </SettingsCard>
      <SettingsCard
        title="Guardrails"
        subtitle="What Addy is allowed to do without your approval, and where she must stop and ask."
      >
        <SettingsToggle checked={addy.drafts} onChange={(drafts) => updateAddy({ drafts })} label="Draft buyer messages" desc="Prepare email, Slack, LinkedIn, or WhatsApp copy." />
        <SettingsToggle checked={addy.buyerProofOnly} onChange={(buyerProofOnly) => updateAddy({ buyerProofOnly })} label="Require buyer-proof framing" desc="Every recommendation must name the buyer signal it is trying to create." />
        <SettingsToggle checked={addy.managerCoaching} onChange={(managerCoaching) => updateAddy({ managerCoaching })} label="Manager coaching mode" desc="Convert buyer gaps into rep coaching moves in manager view." />
      </SettingsCard>
      <SettingsCard
        title="Buyer-proof thresholds"
        subtitle="The signals that decide when a deal becomes buyer-unverified or forecast-at-risk."
      >
        <label className="settings-range">
          <span><b>Stale buyer signal</b><em>{signals.staleDays} days without buyer movement</em></span>
          <input type="range" min="3" max="21" value={signals.staleDays} onChange={(e) => updateSignals({ staleDays: Number(e.target.value) })} />
        </label>
        <label className="settings-range">
          <span><b>Buyer-seller gap</b><em>{signals.gapThreshold} pt before warning</em></span>
          <input type="range" min="5" max="35" value={signals.gapThreshold} onChange={(e) => updateSignals({ gapThreshold: Number(e.target.value) })} />
        </label>
      </SettingsCard>
      <SettingsCard
        title="Required proof"
        subtitle="Deals missing any of these are flagged as forecast risk."
      >
        <SettingsToggle checked={signals.economicBuyerRequired} onChange={(economicBuyerRequired) => updateSignals({ economicBuyerRequired })} label="Economic buyer identified" desc="Flag proposal or negotiation deals without a known owner." />
        <SettingsToggle checked={signals.nextStepRequired} onChange={(nextStepRequired) => updateSignals({ nextStepRequired })} label="Buyer-owned next step" desc="Require date, owner, and buyer-side acceptance." />
        <SettingsToggle checked={signals.activityPenalty} onChange={(activityPenalty) => updateSignals({ activityPenalty })} label="Penalize seller-only activity" desc="Lower confidence when rep motion rises without buyer movement." />
      </SettingsCard>
    </div>
  );

  const renderCurrency = () => {
    const previewAmount = 1234567;
    return (
      <div className="settings-page">
        <SettingsCard
          title="Default currency"
          subtitle="Currency used to display deal amounts, forecasts, and goals across the workspace."
        >
          <SettingsSelect
            label="Primary currency"
            value={currency.primary}
            onChange={(primary) => updateCurrency({ primary })}
            options={CURRENCIES.map((c) => ({ value: c.code, label: c.label }))}
          />
          <div className="settings-form-grid">
            <SettingsSelect
              label="Symbol position"
              value={currency.symbolPosition}
              onChange={(symbolPosition) => updateCurrency({ symbolPosition })}
              options={[
                { value: "prefix", label: "Before amount" },
                { value: "suffix", label: "After amount" },
              ]}
            />
            <SettingsSelect
              label="Decimal places"
              value={String(currency.decimalPlaces)}
              onChange={(v) => updateCurrency({ decimalPlaces: Number(v) })}
              options={[{ value: "0", label: "0 (compact)" }, { value: "2", label: "2 (precise)" }]}
            />
          </div>
          <div className="settings-target-callout">
            <b>{formatCurrency(previewAmount, currency.primary, currency.symbolPosition)}</b>
            <em>Preview · 1,234,567 in your currency</em>
          </div>
        </SettingsCard>
      </div>
    );
  };

  const renderImportExport = () => (
    <div className="settings-page">
      <SettingsCard
        title="Connected systems"
        subtitle="CRM, email, calendar, and workspace tools that provide buyer-proof signals."
        action={<span className="settings-card-meta">3 healthy · 1 needs review</span>}
      >
        <div className="settings-integration-list">
          {SETTINGS_INTEGRATIONS.map((item) => (
            <article key={item.id} className={`settings-integration tone-${item.tone}`}>
              <span className="settings-integration-icon">
                <Icon name={
                  item.id === "slack" ? "chat" :
                  item.id === "calendar" ? "calendar" :
                  item.id === "gmail" ? "mail" :
                  item.id === "whatsapp" ? "phone" :
                  item.id === "hubspot" ? "grid" :
                  "route"
                } size={15} />
              </span>
              <div>
                <b>{item.name}</b>
                <em>{item.detail}</em>
              </div>
              <span className="settings-integration-sync">{item.lastSync}</span>
              <span className={`settings-status tone-${item.tone}`}>{item.status}</span>
              <button type="button" className="settings-secondary-btn sm">Manage</button>
            </article>
          ))}
        </div>
      </SettingsCard>
      <SettingsCard
        title="Data exchange"
        subtitle="One-off CSV import or export of deals, contacts, and proof events."
        footer={
          <div className="settings-action-row">
            <button type="button" className="settings-secondary-btn">Export deals</button>
            <button type="button" className="settings-primary-btn">Import CSV</button>
          </div>
        }
      >
        <p className="settings-panel-copy">Last export: never. Last import: never. CSV column mapping is preserved per source so repeated imports stay clean.</p>
      </SettingsCard>
    </div>
  );

  const renderNotifications = () => (
    <div className="settings-page">
      <SettingsCard
        title="Where Nudge interrupts"
        subtitle="Quiet defaults for repeated work, louder alerts only when buyer proof or forecast quality changes."
      >
        <SettingsToggle checked={notifications.forecastRisk} onChange={(forecastRisk) => updateNotifications({ forecastRisk })} label="Forecast risk alerts" desc="When commit dollars lose buyer-backed support." />
        <SettingsToggle checked={notifications.coaching} onChange={(coaching) => updateNotifications({ coaching })} label="Manager coaching prompts" desc="When a rep needs a precise challenge before review." />
        <SettingsToggle checked={notifications.buyerReplies} onChange={(buyerReplies) => updateNotifications({ buyerReplies })} label="Buyer replies and accepted next steps" desc="Positive proof that should update the deal read." />
        <SettingsToggle checked={notifications.weeklyDigest} onChange={(weeklyDigest) => updateNotifications({ weeklyDigest })} label="Weekly digest" desc="One summary of proof gained, proof missing, and forecast change." />
      </SettingsCard>
    </div>
  );

  const updateUseCase = (id, edits) => {
    updateHeadless({
      useCases: {
        ...headless.useCases,
        [id]: { ...(headless.useCases[id] || {}), ...edits },
      },
    });
  };

  const renderHeadless = () => {
    const maskedKey = headless.apiKey.replace(/^(ndg_live_)(.+)$/, (_m, prefix, rest) => prefix + "•".repeat(rest.length));
    const enabledCount = HEADLESS_USE_CASES.filter((uc) => headless.useCases[uc.id]?.enabled).length;
    return (
      <div className="settings-page">
        <SettingsCard
          eyebrow="Developer · Beta"
          title="Headless access"
          subtitle="Run Nudge as a backend service. Addy fires actions through your own delivery surfaces instead of the in-app UI."
          action={
            <span className={`settings-pill-status ${headless.enabled ? "is-on" : ""}`}>
              {headless.enabled ? "Live" : "Disabled"}
            </span>
          }
        >
          <SettingsToggle
            checked={headless.enabled}
            onChange={(enabled) => updateHeadless({ enabled })}
            label="Enable headless mode"
            desc="When on, Addy stops surfacing prompts in the UI and dispatches events to your webhook or default channel instead."
          />
          <div className="settings-field">
            <span>API key</span>
            <div className="settings-input-shell settings-apikey-shell">
              <code className="settings-apikey-value">{apiKeyRevealed ? headless.apiKey : maskedKey}</code>
              <button type="button" className="settings-apikey-action" onClick={() => setApiKeyRevealed((v) => !v)}>
                <Icon name="eye" size={14} />
                <span>{apiKeyRevealed ? "Hide" : "Reveal"}</span>
              </button>
              <button type="button" className="settings-apikey-action" onClick={() => navigator.clipboard && navigator.clipboard.writeText(headless.apiKey)}>
                <Icon name="copy" size={13} />
                <span>Copy</span>
              </button>
              <button type="button" className="settings-apikey-action danger" onClick={regenerateApiKey}>
                <Icon name="bolt" size={13} />
                <span>Regenerate</span>
              </button>
            </div>
            <em className="settings-phone-helper">Rotates instantly. Old key keeps working for 30 minutes after regeneration.</em>
          </div>
          <SettingsField
            label="Webhook URL"
            type="url"
            value={headless.webhookUrl}
            placeholder="https://your-domain.tld/nudge/events"
            onChange={(webhookUrl) => updateHeadless({ webhookUrl })}
          />
        </SettingsCard>

        <SettingsCard
          eyebrow="Use cases · Channels"
          title="Where each event lands"
          subtitle="Each Addy use case has its own delivery channel and timing. Disable a row to keep that event inside the app."
          action={<span className="settings-card-meta">{enabledCount} / {HEADLESS_USE_CASES.length} active</span>}
        >
          <div className="settings-usecase-list">
            {HEADLESS_USE_CASES.map((uc) => {
              const state = headless.useCases[uc.id] || { enabled: false, channel: HEADLESS_CHANNELS[0].value, timing: "0" };
              return (
                <article key={uc.id} className={`settings-usecase ${state.enabled ? "is-on" : ""}`}>
                  <span className="settings-usecase-icon"><Icon name={uc.icon} size={15} /></span>
                  <div className="settings-usecase-copy">
                    <b>{uc.name}</b>
                    <em>{uc.desc}</em>
                  </div>
                  <label className="settings-usecase-field">
                    <span>Channel</span>
                    <div className="settings-input-shell sm">
                      <select
                        value={state.channel}
                        onChange={(e) => updateUseCase(uc.id, { channel: e.target.value })}
                        disabled={!state.enabled}
                      >
                        {HEADLESS_CHANNELS.map((c) => (
                          <option key={c.value} value={c.value}>{c.label}</option>
                        ))}
                      </select>
                    </div>
                  </label>
                  {uc.timing ? (
                    <label className="settings-usecase-field settings-usecase-timing">
                      <span>{uc.timing.label}</span>
                      <div className="settings-input-shell sm">
                        <input
                          type="number"
                          min="0"
                          max="120"
                          value={state.timing}
                          onChange={(e) => updateUseCase(uc.id, { timing: e.target.value })}
                          disabled={!state.enabled}
                        />
                        <span className="settings-usecase-timing-unit">{uc.timing.unit}</span>
                      </div>
                    </label>
                  ) : (
                    <span className="settings-usecase-spacer" aria-hidden="true" />
                  )}
                  <label className="settings-usecase-toggle" aria-label={`${state.enabled ? "Disable" : "Enable"} ${uc.name}`}>
                    <span className={`settings-switch ${state.enabled ? "is-on" : ""}`} aria-hidden="true"><span /></span>
                    <input
                      type="checkbox"
                      checked={state.enabled}
                      onChange={(e) => updateUseCase(uc.id, { enabled: e.target.checked })}
                    />
                  </label>
                </article>
              );
            })}
          </div>
        </SettingsCard>

        <SettingsCard
          title="Quiet hours"
          subtitle="Window when Addy stops dispatching across every channel. Events received during quiet hours queue and fire at the window's end."
        >
          <div className="settings-form-grid">
            <SettingsField
              label="Start"
              type="time"
              value={headless.quietHoursStart}
              onChange={(quietHoursStart) => updateHeadless({ quietHoursStart })}
            />
            <SettingsField
              label="End"
              type="time"
              value={headless.quietHoursEnd}
              onChange={(quietHoursEnd) => updateHeadless({ quietHoursEnd })}
            />
          </div>
          <div className="settings-compliance-box">
            <b>Current policy</b>
            <p>Headless dispatch is paused from <strong>{headless.quietHoursStart}</strong> to <strong>{headless.quietHoursEnd}</strong>. Use-case channels resume automatically at the window's end.</p>
          </div>
        </SettingsCard>
      </div>
    );
  };

  const renderSecurity = () => (
    <div className="settings-page">
      <SettingsCard
        title="Access controls"
        subtitle="Identity, auditability, and how buyer data is displayed to people without deal access."
      >
        <SettingsToggle checked={security.sso} onChange={(sso) => updateSecurity({ sso })} label="Require SSO" desc="Force SAML or Google Workspace login for all users." />
        <SettingsToggle checked={security.auditLog} onChange={(auditLog) => updateSecurity({ auditLog })} label="Audit log" desc="Track admin changes, integrations, and action approvals." />
        <SettingsToggle checked={security.piiMasking} onChange={(piiMasking) => updateSecurity({ piiMasking })} label="Mask sensitive buyer data" desc="Hide phone/email details from users without deal access." />
      </SettingsCard>
      <SettingsCard
        title="Data retention"
        subtitle="How long Nudge keeps evidence metadata after a deal closes or goes dark."
      >
        <SettingsSelect
          label="Activity retention"
          value={security.dataRetention}
          onChange={(dataRetention) => updateSecurity({ dataRetention })}
          options={["6 months", "12 months", "18 months", "24 months"].map((m) => ({ value: m, label: m }))}
        />
        <div className="settings-compliance-box">
          <b>Current policy</b>
          <p>Keep evidence metadata for {security.dataRetention}. Buyer message bodies are referenced by source and not copied into Nudge unless approved.</p>
        </div>
      </SettingsCard>
    </div>
  );

  const content = {
    profile: renderProfile,
    workspace: renderWorkspace,
    team: renderTeam,
    salesStudio: renderSalesStudio,
    intelligence: renderIntelligence,
    headless: renderHeadless,
    currency: renderCurrency,
    importExport: renderImportExport,
    notifications: renderNotifications,
    security: renderSecurity,
  }[active];

  return (
    <div className="settings-module" data-screen-label="Settings">
      <nav className="settings-tabs" aria-label="Settings sections">
        {SETTINGS_SECTIONS.map((section) => (
          <button
            key={section.id}
            type="button"
            className={`settings-tab ${active === section.id ? "is-active" : ""}`}
            data-tour={`settings-tab-${section.id}`}
            onClick={() => setActive(section.id)}
          >
            <span>{section.label}</span>
          </button>
        ))}
      </nav>
      <main className="settings-content">
        {content && content()}
        <footer className="settings-footer">
          <span>Saved in this browser.</span>
          <div>
            <button type="button" className="settings-secondary-btn" onClick={resetToDefaults}>Reset defaults</button>
            <button type="button" className="settings-primary-btn" onClick={() => onSave && onSave(currentSettings)}>Save settings</button>
          </div>
        </footer>
      </main>
    </div>
  );
}

window.NUDGE_SETTINGS_DEFAULTS = NUDGE_SETTINGS_DEFAULTS;
window.mergeNudgeSettings = mergeNudgeSettings;
window.SettingsModule = SettingsModule;
window.SETTINGS_SECTIONS = SETTINGS_SECTIONS;
