/* Account 360 — single account detail view */

const { useState: useStateAD } = React;

function PageAccountDetail({ companyId, onNavigate }) {
  const company = getCompany(companyId) || window.COMPANIES[0];
  if (!company) {
    return (
      <>
        <PageHeader title="Account" subtitle="Loading…" />
        <div style={{ padding: "80px 24px", textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>
          {window.COMPANIES.length === 0
            ? "No accounts loaded yet. Live data should appear once the boot fetch completes."
            : "Account not found."}
        </div>
      </>
    );
  }
  const api = company.api;
  const [tab, setTab] = useStateAD("overview");

  const stakeholders = window.CONTACTS.filter(c => c.companyId === company.id);
  const opps         = window.OPPORTUNITIES.filter(o => o.companyId === company.id);
  const tasks        = window.TASKS.filter(t => t.companyId === company.id);
  const conv         = window.CONVERSATIONS.filter(c => c.companyId === company.id);

  return (
    <>
      <PageHeader
        title={<span style={{ display: "inline-flex", alignItems: "center", gap: 14 }}>
          <CompanyLogo company={company} size={36} />
          <span>{company.name}</span>
          <LifecyclePill stage={company.abm.lifecycleStage} />
          {company.gtmPriority === "high" && <Badge tone="warm" size="sm" icon="flag">P0 priority</Badge>}
        </span>}
        subtitle={<span>{company.description}</span>}
        actions={<>
          <Button size="md" icon="external" title={company.domain ? `Open ${company.domain}` : "Open website"}
            style={{ width: 36, padding: 0, justifyContent: "center", borderRadius: 999 }}
            onClick={() => window.open(api && api.website ? api.website : `https://${company.domain}`, "_blank")} />
          <Button size="md" icon="linkedin" title="Open LinkedIn page"
            style={{ width: 36, padding: 0, justifyContent: "center", borderRadius: 999, color: "var(--blue-ink, var(--ink))" }}
            onClick={() => api && api.linkedin_url && window.open(api.linkedin_url, "_blank")} />
          <Button size="md" icon="refresh" title="Sync from LinkedIn"
            style={{ width: 36, padding: 0, justifyContent: "center", borderRadius: 999 }} />
          <Button kind="accent" size="md" icon="plus" title="Create new opportunity">Opportunity</Button>
        </>}
        tabs={<>
          <Tab active={tab === "overview"}    onClick={() => setTab("overview")}>Overview</Tab>
          <Tab active={tab === "stakeholders"} onClick={() => setTab("stakeholders")} badge={stakeholders.length}>Contacts</Tab>
          <Tab active={tab === "pipeline"}    onClick={() => setTab("pipeline")} badge={opps.length}>Pipeline</Tab>
          <Tab active={tab === "conversations"} onClick={() => setTab("conversations")} badge={conv.length}>Conversations</Tab>
          <Tab active={tab === "tasks"}       onClick={() => setTab("tasks")} badge={tasks.filter(t => t.status !== "done").length}>Tasks</Tab>
          <Tab active={tab === "signals"}     onClick={() => setTab("signals")}>Signals</Tab>
          <Tab active={tab === "content"}     onClick={() => setTab("content")}>Recommended</Tab>
        </>}
      />

      <div className="page-pad page-pad-y">
        {tab === "overview"     && <AccountOverview company={company} stakeholders={stakeholders} conv={conv} onNavigate={onNavigate} />}
        {tab === "stakeholders" && <AccountStakeholders stakeholders={stakeholders} onNavigate={onNavigate} />}
        {tab === "pipeline"     && <AccountPipeline opps={opps} onNavigate={onNavigate} />}
        {tab === "conversations" && <AccountConversations conv={conv} onNavigate={onNavigate} />}
        {tab === "tasks"        && <AccountTasks tasks={tasks} />}
        {tab === "signals"      && <AccountSignals company={company} />}
        {tab === "content"      && <AccountContent />}
      </div>
    </>
  );
}

/* ───── Overview ───── */
function AccountOverview({ company, stakeholders, conv, onNavigate }) {
  const api = company.api;
  return (
    <div className="ad-overview-grid">
      <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>

        {/* Executive English target — primary signal from the API. */}
        {api ? <ExecutiveEnglishTargetCard api={api} /> : <ScoreStrip abm={company.abm} />}

        {/* Score breakdown — only when API data is present. */}
        {api && <ScoreBreakdownCard api={api} />}

        {/* Next best action / sales reason. The API ships a sales reason string;
            fall back to the legacy abm.nextBestAction otherwise. */}
        <Card padding={0}>
          <div style={{ padding: "14px 18px", display: "flex", alignItems: "center", gap: 10, borderBottom: "1px solid var(--line)" }}>
            <Icon name="sparkles" size={14} style={{ color: "var(--accent)" }} />
            <span style={{ fontSize: 13, fontWeight: 600 }}>{api ? "Why this account" : "Next best action"}</span>
            <AIChip>updated 2h ago</AIChip>
            <span style={{ flex: 1 }} />
            <Button size="sm" icon="refresh" kind="ghost">Regenerate</Button>
          </div>
          <div style={{ padding: "16px 18px", display: "grid", gridTemplateColumns: "1fr auto", gap: 16, alignItems: "center" }}>
            <div>
              <div style={{ fontSize: 14, color: "var(--ink)", lineHeight: 1.55 }}>
                {(api && api.executive_english_sales_reason) || company.abm.nextBestAction}
              </div>
              <div style={{ display: "flex", gap: 8, marginTop: 12, flexWrap: "wrap" }}>
                <Badge tone="violet" icon="zap" size="sm">High impact</Badge>
                <Badge tone="neutral" icon="clock" size="sm">~5 minutes</Badge>
                <Badge tone="green"   icon="circle-check" size="sm">Auto-personalize available</Badge>
              </div>
            </div>
            <div style={{ display: "flex", gap: 6 }}>
              <Button size="md" icon="clock">Snooze</Button>
              <Button kind="accent" size="md" icon="send">Do it</Button>
            </div>
          </div>
        </Card>

        {/* International footprint — operating countries split by language */}
        {api && <CountryFootprintCard api={api} />}

        {/* Locations list — every office with its language scores */}
        {api && api.locations && api.locations.length > 0 && <LocationsCard locations={api.locations} />}

        {/* Buying committee map */}
        <Card padding={0}>
          <SectionHeader title="Buying committee" right={
            <div style={{ display: "flex", gap: 6 }}>
              <Button kind="ghost" size="sm" icon="user-plus">Map contact</Button>
              <Button kind="ghost" size="sm" icon="sparkles" style={{ color: "var(--accent)" }}>AI map</Button>
            </div>
          } />
          {stakeholders.length === 0 ? (
            <EmptyState icon="users" title="No contacts mapped" body="Add the decision makers, champions, and economic buyers for this account." />
          ) : (
            <div style={{ padding: 16, display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))", gap: 12 }}>
              {stakeholders.map(c => (
                <StakeholderCard key={c.id} contact={c} onClick={() => onNavigate("conversations", { conversationId: window.CONVERSATIONS.find(cv => cv.contactId === c.id)?.id })} />
              ))}
            </div>
          )}
        </Card>

        {/* Recent activity */}
        <Card padding={0}>
          <SectionHeader title="Recent activity" />
          <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 14 }}>
            <ActivityItem icon="user-check" tone="green" title="Connected with Pilar Montenegro" meta="LinkedIn · 1d ago" />
            <ActivityItem icon="sparkles"   tone="violet" title="AI generated account brief" meta="Auto · 14h ago" />
            <ActivityItem icon="edit"       tone="warm" title="Sales Lead added a note" meta="Note · 14h ago" />
            <ActivityItem icon="send"       tone="blue" title="Draft message ready for Pilar" meta="LinkedIn draft · 4h ago" />
            <ActivityItem icon="check"      tone="green" title="LinkedIn relations sync completed" meta={`137 contacts synced · ${fmtRelative("2026-05-20T04:08:33.842Z")}`} />
          </div>
        </Card>
      </div>

      {/* Right rail */}
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <Card>
          <SectionTitle>Account profile</SectionTitle>
          <DefList items={[
            api && api.tagline && ["Tagline",
              <span style={{ fontStyle: "italic", color: "var(--ink-2)" }}>“{api.tagline}”</span>
            ],
            ["Industry",  company.industry],
            api && api.parent_category && api.parent_category !== company.industry &&
              ["Category", <span style={{ color: "var(--ink-2)" }}>{api.parent_category}</span>],
            ["Founded",   company.yearFounded || "—"],
            ["Employees", <span className="mono num">{(company.employeeCount || 0).toLocaleString()}</span>],
            api && typeof api.follower_count === "number" && ["LinkedIn followers",
              <span className="mono num">{api.follower_count.toLocaleString()}</span>
            ],
            ["HQ",        `${company.hqCity}${company.hqCountry ? ", " + company.hqCountry : ""}`],
            api && api.hq_full_address && api.hq_full_address !== `${company.hqCity}, ${company.hqCountry}` &&
              ["Address", <span style={{ color: "var(--ink-2)", fontSize: 12 }}>{api.hq_full_address}</span>],
            ["Domain",
              <a href={api && api.website ? api.website : `https://${company.domain}`} target="_blank" rel="noreferrer"
                 className="mono" style={{ color: "var(--blue-ink)" }}>{company.domain}</a>],
            api && api.linkedin_url && ["LinkedIn",
              <a href={api.linkedin_url} target="_blank" rel="noreferrer"
                 style={{ color: "var(--blue-ink)", display: "inline-flex", alignItems: "center", gap: 4 }}>
                <Icon name="linkedin" size={11} /> View profile
              </a>],
            api && api.updatedAt && ["Updated",
              <span style={{ color: "var(--ink-3)" }} className="mono">{fmtRelative(api.updatedAt)}</span>
            ],
            ["Owner",     <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
              <Avatar name={getUser(company.owner)?.name} size={18} />
              {getUser(company.owner)?.name}
            </span>],
          ].filter(Boolean)} />
        </Card>

        {/* Languages — what the company actually operates in */}
        {api && api.officialLanguages && api.officialLanguages.length > 0 && (
          <Card>
            <SectionTitle>Official languages</SectionTitle>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
              {api.officialLanguages.filter(l => l && l !== "None at federal level").map(l => (
                <Badge key={l} tone="blue">{l}</Badge>
              ))}
            </div>
          </Card>
        )}

        <Card>
          <SectionTitle>Tags</SectionTitle>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
            {company.tags.map(t => <Badge key={t} tone="neutral">#{t}</Badge>)}
          </div>
        </Card>

        {company.specialties && company.specialties.length > 0 && (
          <Card>
            <SectionTitle>Specialties</SectionTitle>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
              {company.specialties.slice(0, 12).map(s => <Badge key={s} tone="violet">{s}</Badge>)}
            </div>
          </Card>
        )}

        {company.technologies && company.technologies.length > 0 && (
          <Card>
            <SectionTitle>Tech stack</SectionTitle>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
              {company.technologies.map(t => <Badge key={t} tone="blue">{t}</Badge>)}
            </div>
          </Card>
        )}

        {company.competitors && company.competitors.length > 0 && (
          <Card>
            <SectionTitle>Competitors</SectionTitle>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {company.competitors.map(t => (
                <div key={t} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5 }}>
                  <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--warm)" }} />
                  {t}
                </div>
              ))}
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}

/* ─── Executive English target hero card ─────────────────────────────
   Surfaces the rolled-up target score, tier, and headline counts that
   drive priority for the Executive English sales motion. */
function ExecutiveEnglishTargetCard({ api }) {
  const tier  = api.executive_english_target_tier || "low_priority";
  const tone  = window.TIER_TONE[tier] || "neutral";
  const label = window.TIER_LABEL[tier] || tier;
  const score = Math.round((api.executive_english_target_score || 0) * 10) / 10; /* keep one decimal */
  return (
    <Card padding={0}>
      <div style={{ padding: "14px 18px", display: "flex", alignItems: "center", gap: 10, borderBottom: "1px solid var(--line)" }}>
        <Icon name="trending-up" size={14} style={{ color: "var(--accent)" }} />
        <span style={{ fontSize: 13, fontWeight: 600 }}>Executive English target</span>
        <Badge tone={tone} size="sm" dot>{label}</Badge>
        <span style={{ flex: 1 }} />
        <span style={{ fontSize: 11, color: "var(--ink-4)" }} className="mono">tier_score · 0–10</span>
      </div>
      <div style={{ padding: "18px 20px", display: "grid", gridTemplateColumns: "auto 1fr", gap: 24, alignItems: "center" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <ScoreRing value={score * 10} size={64} stroke={5} tone={tone} />
          <div style={{ lineHeight: 1.1 }}>
            <div className="mono num" style={{ fontSize: 38, fontWeight: 600, color: "var(--ink)", letterSpacing: "-0.02em" }}>
              {score.toFixed(1)}
              <span style={{ fontSize: 16, color: "var(--ink-4)", fontWeight: 500 }}>/10</span>
            </div>
            <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em" }}>
              Target score
            </div>
          </div>
        </div>
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(110px, 1fr))",
          gap: 0,
          borderLeft: "1px solid var(--line)",
        }}>
          <MetricTile
            label="Countries"
            value={api.operatingCountryCount || 0}
            sub={(api.operatingCountryCount === 1 ? "single-country" : "multi-country")}
          />
          <MetricTile
            label="Locations"
            value={api.totalLocationsCount || (api.locations ? api.locations.length : 0)}
            sub={`${api.outsideSpainLocationCount || 0} outside Spain`}
          />
          <MetricTile
            label="English-strong"
            value={api.highestLanguageEnglishCountryCount || 0}
            sub={`${Math.round((api.highestLanguageEnglishCountryRatio || 0) * 100)}% of countries`}
            tone="blue"
          />
          <MetricTile
            label="Spanish-strong"
            value={api.highestLanguageSpanishCountryCount || 0}
            sub={`${api.spainLocationCount || 0} office${(api.spainLocationCount || 0) === 1 ? "" : "s"} in ES`}
            tone="warm"
          />
        </div>
      </div>
    </Card>
  );
}

function MetricTile({ label, value, sub, tone = "neutral" }) {
  const toneColor = ({ blue: "var(--blue-ink)", warm: "var(--warm-ink)", green: "var(--green-ink)", violet: "var(--accent-ink)" })[tone] || "var(--ink)";
  return (
    <div style={{
      padding: "8px 14px",
      borderRight: "1px solid var(--line)",
      lineHeight: 1.1,
    }}>
      <div style={{ fontSize: 10, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em" }}>{label}</div>
      <div className="mono num" style={{ fontSize: 22, fontWeight: 600, color: toneColor, letterSpacing: "-0.01em", marginTop: 3 }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

/* ─── Sub-score breakdown ─────────────────────────────────────────────
   The API ships an 8-item breakdown driving the rolled-up tier score.
   Surface each as a horizontal bar so the user can see the ranking. */
function ScoreBreakdownCard({ api }) {
  const b = api.executive_english_score_breakdown || {};
  const items = [
    { key: "gtm_priority_score",    label: "GTM priority",        tone: "violet" },
    { key: "internationalization",  label: "Internationalization", tone: "blue" },
    { key: "executive_need",        label: "Executive need",      tone: "accent" },
    { key: "english_country_ratio", label: "English-country ratio", tone: "green" },
    { key: "outside_spain_ratio",   label: "Outside-Spain ratio", tone: "blue" },
    { key: "size_score",            label: "Company size",        tone: "neutral" },
    { key: "budget",                label: "Budget signal",       tone: "warm" },
    { key: "decision_speed",        label: "Decision speed",      tone: "violet" },
  ];
  return (
    <Card padding={0}>
      <SectionHeader title="Score breakdown" right={
        <span style={{ fontSize: 11, color: "var(--ink-4)" }} className="mono">all scores · 0–10</span>
      } />
      <div style={{
        padding: "14px 18px",
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))",
        columnGap: 28, rowGap: 12,
      }}>
        {items.map(it => {
          const v = b[it.key];
          const value = typeof v === "number" ? v : 0;
          const pct = Math.max(0, Math.min(100, value * 10));
          const colorMap = {
            violet: "var(--accent)", blue: "var(--blue)", green: "var(--green)",
            warm:   "var(--warm)",   neutral: "var(--ink-3)", accent: "var(--accent)",
          };
          const color = colorMap[it.tone] || colorMap.neutral;
          return (
            <div key={it.key}>
              <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 5 }}>
                <span style={{ fontSize: 12, color: "var(--ink-2)", fontWeight: 500 }}>{it.label}</span>
                <span className="mono num" style={{ fontSize: 12.5, color: "var(--ink)", fontWeight: 600 }}>
                  {value.toFixed(value % 1 === 0 ? 0 : 2)}
                  <span style={{ color: "var(--ink-4)", fontWeight: 500 }}>/10</span>
                </span>
              </div>
              <div style={{ height: 5, borderRadius: 3, background: "var(--inset)", overflow: "hidden" }}>
                <div style={{
                  width: `${pct}%`, height: "100%",
                  background: color,
                  borderRadius: 3,
                  transition: "width 320ms cubic-bezier(0.16,1,0.3,1)",
                }} />
              </div>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

/* ─── International footprint ─────────────────────────────────────────
   Side-by-side English-strong vs Spanish-strong country lists, plus the
   full operating-countries list. */
function CountryFootprintCard({ api }) {
  const en = api.highestLanguageEnglishCountries || [];
  const es = api.highestLanguageSpanishCountries || [];
  const allOps = api.operatingCountries || [];
  const otherCountries = allOps.filter(c => !en.includes(c) && !es.includes(c));
  const enRatio = Math.round((api.highestLanguageEnglishCountryRatio || 0) * 100);
  const esCount = api.highestLanguageSpanishCountryCount || 0;
  return (
    <Card padding={0}>
      <SectionHeader title="International footprint" right={
        <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>
          <span className="mono num" style={{ color: "var(--ink)", fontWeight: 600 }}>{allOps.length}</span> country{allOps.length === 1 ? "" : "s"}
        </span>
      } />
      <div style={{ padding: "14px 18px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
        <FootprintColumn
          title="English strongest"
          icon="globe"
          tone="blue"
          countries={en}
          subtitle={`${enRatio}% of operating countries`}
          empty="No countries where English is the strongest business-language signal."
        />
        <FootprintColumn
          title="Spanish strongest"
          icon="globe"
          tone="warm"
          countries={es}
          subtitle={`${esCount} of ${allOps.length} operating countries`}
          empty="No Spanish-dominant operating countries."
        />
      </div>
      {otherCountries.length > 0 && (
        <div style={{
          padding: "12px 18px 16px",
          borderTop: "1px solid var(--line)",
        }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 8 }}>
            Other operating countries
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
            {otherCountries.map(c => <Badge key={c} tone="neutral">{c}</Badge>)}
          </div>
        </div>
      )}
    </Card>
  );
}

function FootprintColumn({ title, icon, tone, countries, subtitle, empty }) {
  const color = ({ blue: "var(--blue)", warm: "var(--warm)", green: "var(--green)" })[tone] || "var(--ink-3)";
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
        <Icon name={icon} size={12} style={{ color }} />
        <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink)" }}>{title}</span>
        <span className="mono num" style={{ fontSize: 11.5, color: "var(--ink-4)", fontWeight: 500 }}>{countries.length}</span>
      </div>
      <div style={{ fontSize: 11, color: "var(--ink-4)", marginBottom: 8 }}>{subtitle}</div>
      {countries.length === 0 ? (
        <div style={{ fontSize: 11.5, color: "var(--ink-4)", padding: "8px 10px", border: "1px dashed var(--line)", borderRadius: 6, lineHeight: 1.4 }}>
          {empty}
        </div>
      ) : (
        <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
          {countries.map(c => <Badge key={c} tone={tone}>{c}</Badge>)}
        </div>
      )}
    </div>
  );
}

/* ─── Locations list ──────────────────────────────────────────────────
   One row per location. HQ pinned first. Shows the English/Spanish
   language-fit scores so users can spot the best targets per office. */
function LocationsCard({ locations }) {
  const sorted = [...locations].sort((a, b) => (b.is_headquarter ? 1 : 0) - (a.is_headquarter ? 1 : 0));
  return (
    <Card padding={0}>
      <SectionHeader title="Locations" right={
        <span style={{ fontSize: 11.5, color: "var(--ink-3)" }}>
          <span className="mono num" style={{ color: "var(--ink)", fontWeight: 600 }}>{locations.length}</span> office{locations.length === 1 ? "" : "s"}
        </span>
      } />
      <div>
        {sorted.map((loc, i) => (
          <LocationRow key={i} loc={loc} last={i === sorted.length - 1} />
        ))}
      </div>
    </Card>
  );
}

function LocationRow({ loc, last }) {
  const country = loc.countryName || window.countryName(loc.country);
  const isEnglishDominant = loc.highestLanguage === "english";
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "auto 1fr auto auto",
      gap: 14,
      alignItems: "center",
      padding: "12px 18px",
      borderBottom: last ? "none" : "1px solid var(--line)",
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 8,
        background: loc.is_headquarter ? "color-mix(in oklch, var(--accent) 12%, var(--surface))" : "var(--inset)",
        border: "1px solid var(--line)",
        display: "flex", alignItems: "center", justifyContent: "center",
        color: loc.is_headquarter ? "var(--accent)" : "var(--ink-3)",
        flexShrink: 0,
      }}>
        <Icon name={loc.is_headquarter ? "building" : "map-pin"} size={14} />
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 2 }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)" }}>{loc.city}</span>
          <span style={{ fontSize: 12, color: "var(--ink-3)" }}>· {country}</span>
          {loc.is_headquarter && <Badge tone="violet" size="sm">HQ</Badge>}
        </div>
        <div style={{
          fontSize: 11.5, color: "var(--ink-4)",
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
        }} className="mono">
          {loc.full_address || `${loc.line1 || ""}${loc.zipcode ? ", " + loc.zipcode : ""}`}
        </div>
        {(loc.officialLanguages && loc.officialLanguages.length > 0) && (
          <div style={{ fontSize: 10.5, color: "var(--ink-4)", marginTop: 3 }}>
            {loc.officialLanguages.filter(l => l !== "None at federal level").join(" · ")}
          </div>
        )}
      </div>
      <LangChip label="EN" value={loc.english} active={isEnglishDominant} tone="blue" />
      <LangChip label="ES" value={loc.spanish} active={loc.highestLanguage === "spanish"} tone="warm" />
    </div>
  );
}

function LangChip({ label, value, active, tone }) {
  if (typeof value !== "number") return <div style={{ width: 56 }} />;
  const v = Math.max(0, Math.min(10, value));
  const color = ({ blue: "var(--blue)", warm: "var(--warm)" })[tone] || "var(--ink-3)";
  return (
    <div title={`${label} business-language fit: ${v}/10`}
      style={{
        display: "inline-flex", alignItems: "center", gap: 6,
        padding: "3px 7px", borderRadius: 6, minWidth: 60,
        background: active ? `color-mix(in oklch, ${color} 14%, var(--surface))` : "var(--surface-2)",
        border: `1px solid ${active ? `color-mix(in oklch, ${color} 35%, var(--line))` : "var(--line)"}`,
      }}>
      <span style={{
        fontSize: 9.5, fontWeight: 700, letterSpacing: "0.04em",
        color: active ? color : "var(--ink-4)",
      }}>{label}</span>
      <span className="mono num" style={{ fontSize: 12, fontWeight: 600, color: active ? "var(--ink)" : "var(--ink-3)" }}>
        {v}
      </span>
    </div>
  );
}

function BigScore({ label, value, tone }) {
  return (
    <Card padding={16} style={{ display: "flex", alignItems: "center", gap: 14 }}>
      <ScoreRing value={value} size={48} stroke={4} tone={tone} />
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em" }}>{label}</div>
        <div className="mono num" style={{ fontSize: 22, fontWeight: 600, color: "var(--ink)", letterSpacing: "-0.02em", lineHeight: 1.1 }}>{value}</div>
        <div style={{ fontSize: 11, color: "var(--green-ink)", display: "inline-flex", alignItems: "center", gap: 3, marginTop: 1 }}>
          <Icon name="trending-up" size={10} /> +{Math.floor(Math.random() * 8 + 2)}
        </div>
      </div>
    </Card>
  );
}

/* Compact horizontal strip of all four ABM scores. Replaces the 4-card grid. */
function ScoreStrip({ abm }) {
  const items = [
    { label: "Priority",     value: abm.priorityScore,     tone: "violet" },
    { label: "Fit",          value: abm.fitScore,          tone: "green" },
    { label: "Intent",       value: abm.intentScore,       tone: "warm" },
    { label: "Relationship", value: abm.relationshipScore, tone: "blue" },
  ];
  return (
    <Card padding={0}>
      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))",
      }}>
        {items.map((it, i) => (
          <div key={it.label} style={{
            display: "flex", alignItems: "center", gap: 10,
            padding: "10px 14px",
            borderRight: i < items.length - 1 ? "1px solid var(--line)" : "none",
          }}>
            <ScoreRing value={it.value} size={28} stroke={3} tone={it.tone} />
            <div style={{ minWidth: 0, lineHeight: 1.1 }}>
              <div style={{
                fontSize: 10, fontWeight: 600,
                color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em",
              }}>{it.label}</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 5, marginTop: 2 }}>
                <span className="mono num" style={{ fontSize: 15, fontWeight: 600, color: "var(--ink)", letterSpacing: "-0.01em" }}>
                  {it.value}
                </span>
                <span style={{ fontSize: 10, color: "var(--green-ink)", fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 2 }}>
                  <Icon name="trending-up" size={9} />+{Math.floor(Math.random() * 8 + 2)}
                </span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}

function DefList({ items }) {
  return (
    <dl style={{ margin: 0, display: "grid", rowGap: 8 }}>
      {items.map(([k, v], i) => (
        <div key={i} style={{ display: "grid", gridTemplateColumns: "100px 1fr", fontSize: 12.5, alignItems: "center", gap: 12 }}>
          <dt style={{ color: "var(--ink-3)" }}>{k}</dt>
          <dd style={{ margin: 0, color: "var(--ink)", fontWeight: 500 }}>{v}</dd>
        </div>
      ))}
    </dl>
  );
}

function ActivityItem({ icon, tone, title, meta }) {
  const colors = {
    green: "var(--green)", violet: "var(--accent)", warm: "var(--warm)",
    blue: "var(--blue)", neutral: "var(--ink-3)",
  };
  return (
    <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
      <div style={{
        width: 28, height: 28, borderRadius: "50%",
        background: "var(--surface-2)",
        border: `1px solid var(--line)`,
        display: "flex", alignItems: "center", justifyContent: "center",
        color: colors[tone] || colors.neutral,
        flexShrink: 0,
      }}>
        <Icon name={icon} size={13} />
      </div>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ fontSize: 13, color: "var(--ink)" }}>{title}</div>
        <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{meta}</div>
      </div>
    </div>
  );
}

function StakeholderCard({ contact, onClick }) {
  return (
    <button onClick={onClick} style={{
      textAlign: "left", padding: 12,
      border: "1px solid var(--line)", borderRadius: 10,
      background: "var(--surface)",
      display: "flex", flexDirection: "column", gap: 8,
      transition: "border-color 120ms, transform 120ms",
    }}
    onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--line-strong)"; e.currentTarget.style.transform = "translateY(-1px)"; }}
    onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--line)"; e.currentTarget.style.transform = ""; }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <Avatar name={`${contact.firstName} ${contact.lastName}`} src={contact.profilePictureUrl} size={36} />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {contact.firstName} {contact.lastName}
          </div>
          <div style={{ fontSize: 11.5, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {contact.position}
          </div>
        </div>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
        <Badge tone={
          contact.abm.buyingCommitteeRole === "decision_maker" ? "violet"
          : contact.abm.buyingCommitteeRole === "economic_buyer" ? "warm"
          : contact.abm.buyingCommitteeRole === "influencer" ? "blue"
          : "neutral"
        } size="sm">{contact.abm.buyingCommitteeRole.replace(/_/g, " ")}</Badge>
        <Badge tone={
          contact.linkedinStatus === "accepted" ? "green"
          : contact.linkedinStatus === "pending_sent" ? "warm"
          : "neutral"
        } size="sm" dot>{contact.linkedinStatus === "accepted" ? "Connected" : contact.linkedinStatus === "pending_sent" ? "Pending" : "No relation"}</Badge>
      </div>
      <ScoreBar value={contact.abm.relationshipStrength} label="Strength" tone="green" />
    </button>
  );
}

/* ───── Contacts tab ───── */
function AccountStakeholders({ stakeholders, onNavigate }) {
  if (stakeholders.length === 0) {
    return <EmptyState icon="users" title="No contacts" body="Map decision makers, champions, and other buyers for this account." action={<Button kind="primary" icon="user-plus">Find contacts</Button>} />;
  }
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 14 }}>
      {stakeholders.map(c => (
        <StakeholderCard key={c.id} contact={c} onClick={() => {
          const conv = window.CONVERSATIONS.find(cv => cv.contactId === c.id);
          if (conv) onNavigate("conversations", { conversationId: conv.id });
        }} />
      ))}
    </div>
  );
}

/* ───── Pipeline tab ───── */
function AccountPipeline({ opps, onNavigate }) {
  if (opps.length === 0) {
    return <EmptyState icon="kanban" title="No opportunities" body="Create an opportunity to track deal progression for this account." action={<Button kind="primary" icon="plus">New opportunity</Button>} />;
  }
  return (
    <div className="scroll-x">
    <Card padding={0}>
      {opps.map((o, i) => (
        <div key={o.id} style={{
          padding: 16,
          borderBottom: i < opps.length - 1 ? "1px solid var(--line)" : "none",
          display: "grid", gridTemplateColumns: "minmax(280px, 1fr) 120px 120px 120px 90px",
          gap: 16, alignItems: "center",
        }}>
          <div>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>{o.name}</div>
            <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>Next: {o.nextStep}</div>
          </div>
          <Badge tone={({contacted:"blue",proposal:"warm",discovery:"warm",negotiation:"warm",meeting_booked:"violet",research:"neutral",won:"green"})[o.stage]}>{o.stage.replace(/_/g," ")}</Badge>
          <div className="mono num" style={{ fontSize: 14, fontWeight: 600 }}>{fmtCurrency(o.value, o.currency)}</div>
          <div className="mono num" style={{ fontSize: 12 }}>{Math.round(o.probability * 100)}% · {fmtDate(o.closeDate, { day: "2-digit", month: "short" })}</div>
          <div style={{ textAlign: "right" }}>
            <Badge tone={o.risk === "medium" ? "warm" : "green"}>{o.risk} risk</Badge>
          </div>
        </div>
      ))}
    </Card>
    </div>
  );
}

/* ───── Conversations tab ───── */
function AccountConversations({ conv, onNavigate }) {
  return (
    <Card padding={0}>
      {conv.length === 0 ? <EmptyState icon="messages" title="No conversations" /> :
       conv.map((c, i) => {
         const contact = getContact(c.contactId);
         const last = c.messages[c.messages.length - 1];
         return (
           <button key={c.id} onClick={() => onNavigate("conversations", { conversationId: c.id })} style={{
             display: "grid", gridTemplateColumns: "40px 1fr 80px", gap: 14,
             padding: "14px 18px",
             borderBottom: i < conv.length - 1 ? "1px solid var(--line)" : "none",
             alignItems: "center", textAlign: "left", width: "100%",
           }}>
             <Avatar name={`${contact?.firstName} ${contact?.lastName}`} src={contact?.profilePictureUrl} size={32} />
             <div>
               <div style={{ fontSize: 13, fontWeight: 600 }}>{contact?.firstName} {contact?.lastName}</div>
               <div style={{ fontSize: 12, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                 {last?.body?.slice(0, 80)}
               </div>
             </div>
             <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)", textAlign: "right" }}>{fmtRelative(c.lastActivityAt)}</span>
           </button>
         );
       })}
    </Card>
  );
}

function AccountTasks({ tasks }) {
  return <window.TasksList tasks={tasks} />;
}

function AccountSignals({ company }) {
  const signals = [
    { type: "funding",         icon: "trending-up", title: "Reported €18M H1 revenue growth", at: "2026-05-12T00:00:00Z" },
    { type: "company_hiring",  icon: "user-plus",   title: "Posted 4 new HR roles in 30 days",   at: "2026-05-10T00:00:00Z" },
    { type: "post_like",       icon: "star",        title: "Pilar liked our 'Hospitality HR' post", at: "2026-05-19T11:22:00Z" },
    { type: "profile_view",    icon: "eye",         title: "3 contacts viewed our LinkedIn page", at: "2026-05-18T00:00:00Z" },
  ];
  return (
    <Card padding={0}>
      {signals.map((s, i) => (
        <div key={i} style={{
          display: "grid", gridTemplateColumns: "32px 1fr 100px",
          gap: 14, padding: "14px 18px",
          borderBottom: i < signals.length - 1 ? "1px solid var(--line)" : "none",
          alignItems: "center",
        }}>
          <div style={{ width: 28, height: 28, borderRadius: "50%", background: "var(--accent-soft)", color: "var(--accent-ink)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name={s.icon} size={13} />
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{s.title}</div>
            <div style={{ fontSize: 11.5, color: "var(--ink-3)" }} className="mono">{s.type}</div>
          </div>
          <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)", textAlign: "right" }}>{fmtRelative(s.at)}</span>
        </div>
      ))}
    </Card>
  );
}

function AccountContent() {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 14 }}>
      {window.CONTENT.slice(0, 4).map(c => (
        <Card key={c.id} padding={16} style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <Badge tone="violet" size="sm" icon="sparkles">Recommended</Badge>
            <Badge tone="neutral" size="sm">{c.type.replace(/_/g, " ")}</Badge>
          </div>
          <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)" }}>{c.title}</div>
          <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.45 }}>{c.description}</div>
          <div style={{ display: "flex", gap: 6, marginTop: 6 }}>
            <Button size="sm" icon="paperclip">Attach to message</Button>
            <Button size="sm" kind="ghost" icon="eye">Preview</Button>
          </div>
        </Card>
      ))}
    </div>
  );
}

window.PageAccountDetail = PageAccountDetail;
