// HomeContent.jsx: the homepage. Your sources -> Skardi -> the coding agent you
// already use. Needs Shared.jsx and assets/site.css.

const HOME_SOURCES = [
  { name: 'Gmail', icon: skIcon('gmail', 'EA4335') },
  { name: 'GitHub', icon: skIcon('github', '0a1220') },
  { name: 'Notion', icon: skIcon('notion', '0a1220') },
  { name: 'Google Drive', icon: skIcon('googledrive', '4285F4') },
  { name: 'Slack', icon: skIcon('slack', '4A154B') },
  { name: 'Postgres', icon: skIcon('postgresql', '336791') },
  { name: 'MySQL', icon: skIcon('mysql', '00546B') },
  { name: t('Documents'), icon: skIcon('files', '1e3a5f') },
];

// The real setup, copied from the console's "Set up your agent" card
// (skardi-cloud frontend/src/lib/agentSnippets.ts): sign the skardi CLI in
// through the console, then install the skardi skill the way each agent
// takes it. Nothing here is workspace-specific; the console approves the
// workspace in the browser during `skardi login`.
const SKARDI_LOGIN = 'skardi login --control-plane https://console.skardi.ai --no-verify';
const SKILLS_TO_AGENTS_DIR = [
  'd=$(mktemp -d) && git clone --depth 1 https://github.com/SkardiLabs/skardi-skills.git "$d"',
  'mkdir -p ~/.agents/skills && cp -r "$d"/skills/* ~/.agents/skills/',
];
const AGENT_SETUP = {
  'Claude Code': [
    SKARDI_LOGIN,
    'claude plugin marketplace add SkardiLabs/skardi-skills',
    'claude plugin install skardi@skardi-skills',
  ].join('\n'),
  'Codex': [SKARDI_LOGIN, ...SKILLS_TO_AGENTS_DIR].join('\n'),
  'Cursor': [SKARDI_LOGIN, ...SKILLS_TO_AGENTS_DIR].join('\n'),
  'Gemini CLI': [
    SKARDI_LOGIN,
    'gemini extensions install https://github.com/SkardiLabs/skardi-skills',
  ].join('\n'),
};
const SKARDI_CLI_INSTALL_URL = 'https://github.com/SkardiLabs/skardi#install';
const AGENTS = Object.keys(AGENT_SETUP);

const FlowLabel = ({ children }) => (
  <div style={{
    fontFamily: SK_MONO, fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase',
    color: '#6b7e9a', marginBottom: 12,
  }}>{children}</div>
);

const SourceChip = ({ name, icon }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', borderRadius: 10,
    background: '#fff', border: '1px solid rgba(30,58,100,0.12)', boxShadow: '0 1px 4px rgba(30,58,100,0.08)',
    fontSize: 13, fontWeight: 500, color: '#1e3a5f',
  }}>
    <img src={icon} alt="" width="18" height="18" style={{ display: 'block', flexShrink: 0 }} />
    {name}
  </div>
);

const SkardiCardRow = ({ k, v, accent }) => (
  <div style={{
    display: 'flex', justifyContent: 'space-between', gap: 12, padding: '8px 10px', borderRadius: 6,
    background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(125,211,252,0.1)',
  }}>
    <span style={{ color: '#8ea3c0' }}>{k}</span>
    <span style={{ color: accent ? '#2ee89a' : '#e6eef9' }}>{v}</span>
  </div>
);

const HomeHero = ({ activeAgent, setActiveAgent }) => (
  <section className="sk-hero" data-section="hero" style={{
    position: 'relative', overflow: 'hidden', background: 'linear-gradient(180deg, #ffffff 0%, #f2f6fb 100%)',
  }}>
    <GridOverlay mask="radial-gradient(ellipse 70% 70% at 50% 30%, #000 20%, transparent 80%)" />
    <div style={{ position: 'relative', maxWidth: 1100, margin: '0 auto', textAlign: 'center' }}>
      <div style={{ marginBottom: 28 }}><HeroBadge>{t('Works with Claude Code, Codex, Cursor and Gemini CLI')}</HeroBadge></div>
      <h1 style={{
        fontSize: 'clamp(40px, 6vw, 76px)', fontWeight: 700, lineHeight: 1.04, letterSpacing: '-0.035em',
        margin: '0 0 24px', textWrap: 'balance', color: '#0a1220',
      }}>{t("You don't need another agent.")}<br />{t('Your coding agent needs ')}<GradientText>{t('your context')}</GradientText>{t('.')}</h1>
      <p style={{
        fontSize: 20, lineHeight: 1.55, color: '#3a5578', maxWidth: 680, margin: '0 auto 36px', textWrap: 'pretty',
      }}>{t('Skardi manages your personal and work context — Gmail, GitHub, Notion, Google Drive, Slack, databases, documents — and hands it to the coding agent you already use. That agent becomes your work agent.')}</p>
      <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap', marginBottom: 64 }}>
        <a href={SK_LINKS.signup} onClick={skTrack('signup', 'hero')} className="sk-btn sk-btn-primary">{t('Sign up free')}</a>
        <a href="#how" onClick={skTrack('how_it_works', 'hero')} className="sk-btn sk-btn-secondary">{t('See how it works')}</a>
      </div>

      <div className="sk-flow">
        <div>
          <FlowLabel>{t('Your sources')}</FlowLabel>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: 10 }}>
            {HOME_SOURCES.map((s) => <SourceChip key={s.name} {...s} />)}
          </div>
        </div>
        <div className="sk-flow-line is-green" aria-hidden="true" />
        <div style={{
          position: 'relative', padding: '28px 24px', borderRadius: 16, background: '#0a1220', color: '#e6eef9',
          boxShadow: '0 0 0 1px rgba(29,168,105,0.35), 0 12px 40px rgba(29,168,105,0.18)',
        }}>
          <GridOverlay color="rgba(125,211,252,0.06)" radius={16} />
          <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
            <img src="/assets/skardi-mark-tight.png" alt="" style={{ height: 26, width: 'auto' }} />
            <div>
              <div style={{ fontWeight: 700, fontSize: 17 }}>Skardi</div>
              <div style={{ fontFamily: SK_MONO, fontSize: 11, color: '#8ea3c0', letterSpacing: '0.04em' }}>{t('your context, managed')}</div>
            </div>
          </div>
          <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 8, fontFamily: SK_MONO, fontSize: 12.5, lineHeight: 1.5 }}>
            <SkardiCardRow k={t('who')} v={t('you, your team, your projects')} />
            <SkardiCardRow k={t('what')} v={t('threads, docs, PRs, decisions')} />
            <SkardiCardRow k={t('access')} v={t('only what you can see')} accent />
          </div>
        </div>
        <div className="sk-flow-line is-blue" aria-hidden="true" />
        <div>
          <FlowLabel>{t('Your agent')}</FlowLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {AGENTS.map((name) => {
              const on = name === activeAgent;
              return (
                <button key={name} type="button" onClick={() => setActiveAgent(name)} aria-pressed={on}
                  className={`sk-agent-row${on ? ' is-on' : ''}`}
                  style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
                    padding: '12px 14px', borderRadius: 10, background: '#fff', cursor: 'pointer',
                    fontFamily: 'Inter, sans-serif', fontSize: 13, fontWeight: 500, color: '#1e3a5f', textAlign: 'left',
                    border: on ? '1px solid rgba(29,168,105,0.6)' : '1px solid rgba(30,58,100,0.12)',
                    boxShadow: on
                      ? '0 0 0 1px rgba(29,168,105,0.35), 0 8px 32px rgba(29,168,105,0.15)'
                      : '0 1px 4px rgba(30,58,100,0.08)',
                  }}>
                  <span>{name}</span>
                  <span style={{ fontFamily: SK_MONO, fontSize: 10, letterSpacing: '0.06em', color: on ? '#13764a' : '#9aacc2' }}>
                    {on ? t('CONNECTED') : t('READY')}
                  </span>
                </button>
              );
            })}
          </div>
        </div>
      </div>
      <p style={{ margin: '28px auto 0', fontSize: 14, color: '#6b7e9a', maxWidth: 560, textWrap: 'pretty' }}>
        {t('No new app to learn. Keep the agent in your terminal or editor — Skardi just makes it know your work.')}
      </p>
    </div>
  </section>
);

// ---------- How it works: console-style product panels ----------

const panelStyle = {
  borderRadius: 12, border: '1px solid rgba(30,58,100,0.14)', background: '#f2f6fb', padding: 20,
  boxShadow: '0 4px 16px rgba(15,42,74,0.06)', minWidth: 0,
};
const innerCard = { borderRadius: 10, border: '1px solid rgba(30,58,100,0.14)', background: '#fff' };

const PanelHeader = ({ title, sub, right }) => (
  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12, marginBottom: 14 }}>
    <div>
      <div style={{ fontSize: 15, fontWeight: 600, color: '#0a1220', letterSpacing: '-0.01em' }}>{title}</div>
      <div style={{ fontSize: 12, color: '#6b7e9a', marginTop: 2 }}>{sub}</div>
    </div>
    {right}
  </div>
);

const Step = ({ n, color, title, children }) => (
  <div>
    <div style={{ fontFamily: SK_MONO, fontSize: 12, color, marginBottom: 14 }}>{n}</div>
    <h3 style={{ fontSize: 28, fontWeight: 600, margin: '0 0 12px', letterSpacing: '-0.015em', lineHeight: 1.2 }}>{title}</h3>
    <p style={{ fontSize: 16, lineHeight: 1.6, color: '#3a5578', margin: 0, maxWidth: 440 }}>{children}</p>
  </div>
);

const IntegrationCard = ({ name, icon, chip, meta }) => (
  <div style={{ ...innerCard, display: 'flex', flexDirection: 'column', gap: 8, padding: 12, minWidth: 0 }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 600, color: '#0a1220' }}>
      <img src={icon} alt="" width="16" height="16" />{name}
    </div>
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6, minWidth: 0 }}>
      {chip}
      {meta && <span style={{ fontSize: 11, color: '#6b7e9a', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{meta}</span>}
    </div>
  </div>
);

const IntegrationsPanel = () => (
  <div style={panelStyle}>
    <PanelHeader title={t('Integrations')} sub={t('Software your workspace reads from')} right={<StatusChip>{t('6 connected')}</StatusChip>} />
    <div style={autoGrid(140, 10)}>
      <IntegrationCard name="Gmail" icon={skIcon('gmail', 'EA4335')} chip={<StatusChip>{t('Connected')}</StatusChip>} meta="you@acme.com" />
      <IntegrationCard name="GitHub" icon={skIcon('github', '0a1220')} chip={<StatusChip>{t('Connected')}</StatusChip>} meta={t('3 repos')} />
      <IntegrationCard name="Notion" icon={skIcon('notion', '0a1220')} chip={<StatusChip>{t('Connected')}</StatusChip>} meta={t('2 workspaces')} />
      <IntegrationCard name="Slack" icon={skIcon('slack', '4A154B')} chip={<StatusChip tone="syncing" dot>{t('Syncing')}</StatusChip>} meta={t('12 channels')} />
      <IntegrationCard name="Postgres" icon={skIcon('postgresql', '336791')} chip={<StatusChip>{t('Connected')}</StatusChip>} meta="analytics" />
      <IntegrationCard name="MySQL" icon={skIcon('mysql', '00546B')} chip={<StatusChip>{t('Connected')}</StatusChip>} meta="orders" />
      <IntegrationCard name="Google Drive" icon={skIcon('googledrive', '4285F4')} chip={
        <span style={{ fontSize: 12, fontWeight: 600, padding: '3px 10px', borderRadius: 7, border: '1px solid #1da869', color: '#13764a', background: '#fff' }}>{t('Connect')}</span>
      } />
      <div style={{
        display: 'flex', flexDirection: 'column', gap: 8, padding: 12, borderRadius: 10,
        border: '1px dashed rgba(30,58,100,0.22)', background: '#f7fafd',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 600, color: '#0a1220' }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 16, height: 16, borderRadius: 4,
            border: '1px solid rgba(30,58,100,0.3)', fontSize: 11, color: '#3a5578',
          }}>+</span>{t('Documents')}
        </div>
        <div style={{ fontSize: 11, color: '#6b7e9a' }}>{t('Drop PDFs, decks, spreadsheets')}</div>
      </div>
    </div>
  </div>
);

const Stat = ({ label, value }) => (
  <div style={{ ...innerCard, minWidth: 0, padding: 14 }}>
    <div style={{ fontSize: 11, color: '#6b7e9a' }}>{label}</div>
    <div style={{ fontSize: 24, fontWeight: 600, lineHeight: 1.1, color: '#0a1220' }}>{value}</div>
  </div>
);

const FeedRow = ({ icon, text, when, last }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', fontSize: 13, color: '#1e3a5f',
    borderBottom: last ? 'none' : '1px solid rgba(30,58,100,0.06)',
  }}>
    <img src={icon} alt="" width="14" height="14" />
    <span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{text}</span>
    <span style={{ fontSize: 11, color: '#6b7e9a', whiteSpace: 'nowrap' }}>{when}</span>
  </div>
);

const OverviewPanel = () => (
  <div style={panelStyle}>
    <PanelHeader title={t('Overview')} sub={t('Your context, as of 2 minutes ago')} right={
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11, fontWeight: 600, color: '#13764a', whiteSpace: 'nowrap' }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#1da869' }} />{t('Up to date')}
      </span>
    } />
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 10, marginBottom: 10 }}>
      <Stat label={t('Sources')} value="8" />
      <Stat label={t('Items indexed')} value="48,210" />
      <Stat label={t('Projects')} value="7" />
    </div>
    <div style={{ ...innerCard, overflow: 'hidden' }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '10px 14px',
        borderBottom: '1px solid rgba(30,58,100,0.08)',
      }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: '#0a1220' }}>{t('Acme renewal')}</span>
        <StatusChip>{t('Active')}</StatusChip>
      </div>
      <FeedRow icon={skIcon('slack', '4A154B')} text={t('Pricing thread in #acme — 3 open questions')} when={t('2h ago')} />
      <FeedRow icon={skIcon('github', '0a1220')} text={t('PR #214 contract-export — review requested')} when={t('5h ago')} />
      <FeedRow icon={skIcon('notion', '0a1220')} text={t('Renewal plan — decision: annual, net-30')} when={t('Yesterday')} last />
    </div>
  </div>
);

const CopyChip = ({ text }) => {
  const [copied, setCopied] = React.useState(false);
  const copy = async () => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 1600);
    } catch (_) { /* clipboard blocked: the command stays selectable */ }
  };
  return (
    <button type="button" onClick={copy} style={{
      fontFamily: 'Inter, sans-serif', fontSize: 11, fontWeight: 600, padding: '3px 8px', borderRadius: 9999,
      border: 'none', cursor: 'pointer',
      ...(copied ? CHIP_TONES.connected : CHIP_TONES.neutral),
    }}>{copied ? t('Copied') : t('Copy')}</button>
  );
};

const AgentSetupPanel = ({ activeAgent, setActiveAgent }) => (
  <div style={panelStyle}>
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 15, fontWeight: 600, color: '#0a1220', letterSpacing: '-0.01em' }}>{t('Set up your agent')}</div>
      <div style={{ fontSize: 12, color: '#6b7e9a', marginTop: 2 }}>{t('Pick the one you already use')}</div>
    </div>
    <div role="tablist" aria-label={t('Coding agent')} style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 12 }}>
      {AGENTS.map((name) => {
        const on = name === activeAgent;
        return (
          <button key={name} type="button" role="tab" aria-selected={on} onClick={() => setActiveAgent(name)}
            className={`sk-agent-tab${on ? ' is-on' : ''}`}
            style={{
              fontFamily: 'Inter, sans-serif', fontSize: 13, fontWeight: 600, padding: '6px 12px', borderRadius: 8,
              border: 'none', cursor: 'pointer',
              background: on ? '#18905a' : '#fff', color: on ? '#fff' : '#3a5578',
            }}>{name}</button>
        );
      })}
    </div>
    <div style={{ ...innerCard, padding: 14, marginBottom: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginBottom: 8 }}>
        <span style={{ fontSize: 12, color: '#6b7e9a' }}>{t('Run once in your terminal')}</span>
        <CopyChip text={AGENT_SETUP[activeAgent]} />
      </div>
      <div style={{ fontFamily: SK_MONO, fontSize: 12.5, lineHeight: 1.7, color: '#0a1220', overflowX: 'auto', whiteSpace: 'pre' }}>
        {AGENT_SETUP[activeAgent]}
      </div>
      <div style={{ fontSize: 11, color: '#6b7e9a', marginTop: 8 }}>
        {t('Needs the skardi CLI, v0.6 or later.')}{' '}
        <a href={SKARDI_CLI_INSTALL_URL} target="_blank" rel="noopener noreferrer"
          onClick={skTrack('cli_install', 'how_it_works')} className="sk-link">{t('Install guide')}</a>
      </div>
    </div>
    <div style={{ ...innerCard, padding: 14 }}>
      <div style={{ fontSize: 12, color: '#6b7e9a', marginBottom: 8 }}>{t('Then just ask')}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 13, lineHeight: 1.5 }}>
        <div style={{
          alignSelf: 'flex-end', maxWidth: '85%', padding: '8px 12px', borderRadius: '10px 10px 2px 10px',
          background: '#0a1220', color: '#e6eef9',
        }}>{t("Draft the follow-up to Thursday's Acme call")}</div>
        <div style={{
          alignSelf: 'flex-start', maxWidth: '90%', padding: '8px 12px', borderRadius: '10px 10px 10px 2px',
          background: '#f2f6fb', color: '#1e3a5f', border: '1px solid rgba(30,58,100,0.08)',
        }}>
          <span style={{ display: 'block', fontSize: 11, color: '#6b7e9a', marginBottom: 4 }}>{t('Reading calendar · Gmail · Notion via Skardi')}</span>
          {t('Found 3 open items and the pricing question from #acme. Drafting with the net-30 decision from the renewal plan…')}
        </div>
      </div>
    </div>
  </div>
);

const stepRow = (last) => ({ ...autoGrid(300, 48), alignItems: 'center', marginBottom: last ? 0 : 88 });

const HowItWorksSection = ({ activeAgent, setActiveAgent }) => (
  <Section id="how" data-section="how_it_works">
    <Eyebrow>{t('How it works')}</Eyebrow>
    <SectionTitle style={{ marginBottom: 72 }}>{t('Three steps from a coding agent to a work agent')}</SectionTitle>

    <div style={stepRow(false)}>
      <Step n="01" color="#1da869" title={t('Connect your sources')}>
        {t('Sign in to Gmail, GitHub, Notion, Google Drive and Slack, connect databases like Postgres and MySQL, or upload documents. Each one takes a minute, and you can disconnect any time.')}
      </Step>
      <IntegrationsPanel />
    </div>

    {/* The panel comes first in the source so the rows alternate on desktop;
        on a phone it lands above its text, as in the design. */}
    <div style={stepRow(false)}>
      <OverviewPanel />
      <Step n="02" color="#1a8fe0" title={t('Skardi keeps your context current')}>
        {t("It organizes what you work on — people, projects, threads, decisions — and keeps it in sync. Permissions mirror the source: nothing you couldn't already see.")}
      </Step>
    </div>

    <div style={stepRow(true)}>
      <Step n="03" color="#1da869" title={t('Your agent asks Skardi, not you')}>
        {t('Add Skardi to Claude Code, Codex, Cursor or Gemini CLI once — a couple of commands, or one prompt you paste. From then on the agent pulls the context it needs on its own.')}
      </Step>
      <AgentSetupPanel activeAgent={activeAgent} setActiveAgent={setActiveAgent} />
    </div>
  </Section>
);

// ---------- Who it's for ----------

const AUDIENCES = [
  {
    label: t('Individuals'), title: t('Your agent, finally personal'),
    body: t("Connect your own inbox, repos and notes. Your coding agent knows what you're working on, who you're talking to, and what you decided last week."),
    points: [t('Runs locally, your data stays yours'), t('Free to start')],
  },
  {
    label: t('Teams'), title: t('Shared context, no shared spreadsheet'), featured: true,
    body: t("Project context lives in one place, so every teammate's agent gives the same answer about the roadmap, the customer, or the open PR."),
    points: [t('Shared workspaces and projects'), t('Everyone sees only what they already can')],
  },
  {
    label: t('Enterprises'), title: t('Governed context at scale'),
    body: t('Permissions mirror your source systems. Every request is audited. Run it in our cloud or in your own VPC.'),
    points: [t('SSO, audit log, access requests'), t('Self-host option, Apache 2.0 engine')],
  },
];

const WhoSection = () => (
  <Section id="who" tinted data-section="who">
    <Eyebrow>{t("Who it's for")}</Eyebrow>
    <SectionTitle>{t('One context layer, from one person to the whole company')}</SectionTitle>
    <div style={autoGrid(280, 24)}>
      {AUDIENCES.map((a) => (
        <Card key={a.label} accent={a.featured ? '#1da869' : null} style={{ display: 'flex', flexDirection: 'column', padding: 32 }}>
          <CardLabel>{a.label}</CardLabel>
          <h3 style={{ fontSize: 22, fontWeight: 600, margin: '0 0 12px', letterSpacing: '-0.01em' }}>{a.title}</h3>
          <p style={{ fontSize: 15, lineHeight: 1.6, color: '#3a5578', margin: '0 0 24px', flex: 1 }}>{a.body}</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 14, color: '#1e3a5f' }}>
            {a.points.map((p) => (
              <div key={p} style={{ display: 'flex', gap: 10 }}><span style={{ color: '#1da869' }}>—</span>{p}</div>
            ))}
          </div>
        </Card>
      ))}
    </div>
  </Section>
);

const HomeContent = () => {
  // Shared by the hero's agent list and the step-03 tabs.
  const [activeAgent, setActiveAgent] = React.useState('Claude Code');
  return (
    <>
      <HomeHero activeAgent={activeAgent} setActiveAgent={setActiveAgent} />
      <HowItWorksSection activeAgent={activeAgent} setActiveAgent={setActiveAgent} />
      <WhoSection />
      <CTABand subtitle={t("Free for individuals. Team and enterprise plans when you're ready.")} />
    </>
  );
};

window.HomeContent = HomeContent;
