// Endpoint detail page template — renders any /docs/<group>/<name> page from ENDPOINTS data.

const fmtJson = (obj, indent = 2) => JSON.stringify(obj, null, indent);

// Build cURL/JS/Python lines from the request example.
const codeForEndpoint = (ep) => {
  const body = fmtJson(ep.requestExample, 2);
  const bodyLines = body.split('\n');
  const curl = [
    `curl https://api.momentiq.dev${ep.path} \\`,
    `  -H "Authorization: Bearer $MIQ_KEY" \\`,
    `  -H "Content-Type: application/json" \\`,
    `  -d '${body}'`,
  ];
  const js = [
    `const res = await fetch("https://api.momentiq.dev${ep.path}", {`,
    `  method: "${ep.method}",`,
    `  headers: {`,
    `    "Authorization": "Bearer " + process.env.MIQ_KEY,`,
    `    "Content-Type": "application/json",`,
    `  },`,
    `  body: JSON.stringify(${body.replace(/\n/g, '\n  ')}),`,
    `});`,
    `const data = await res.json();`,
  ];
  const py = [
    `import os, requests`,
    ``,
    `r = requests.${ep.method.toLowerCase()}(`,
    `  "https://api.momentiq.dev${ep.path}",`,
    `  headers={"Authorization": f"Bearer {os.environ['MIQ_KEY']}"},`,
    `  json=${body.replace(/: true/g, ': True').replace(/: false/g, ': False').replace(/: null/g, ': None')},`,
    `)`,
    `data = r.json()`,
  ];
  return { curl, js, py };
};

const RelatedCard = ({ id, sourceId }) => {
  const ep = ENDPOINTS[id];
  if (!ep) return null;
  const href = `docs-${id.replace('/','-')}.html`;
  return (
    <a href={href}
      onClick={() => window.MIQAnalytics && window.MIQAnalytics.track('related_endpoint_clicked', {
        endpoint_id: id, endpoint_group: ep.group, from_endpoint_id: sourceId,
      })}
      style={{
        display: 'block', textDecoration: 'none', color: 'inherit',
        background: wf.card, border: `1px solid ${wf.line}`, borderRadius: 10, padding: 14,
      }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
        <Method kind={ep.method} />
        <span style={{ fontFamily: wf.mono, fontSize: 12, color: wf.ink }}>{ep.path}</span>
      </div>
      <div style={{ fontFamily: wf.sans, fontSize: 12.5, color: wf.ink3, lineHeight: 1.5 }}>{ep.short}</div>
    </a>
  );
};

const ExplainerCard = ({ title, items, tone = 'neutral' }) => {
  if (!items || !items.length) return null;
  const colors = {
    does: { bg: 'color-mix(in oklch, var(--accent) 8%, white)', border: 'var(--accent)', label: 'var(--accent)' },
    not: { bg: '#fff7ed', border: '#f97316', label: '#c2410c' },
    good: { bg: '#f0fdf4', border: '#22c55e', label: '#15803d' },
    neutral: { bg: wf.card, border: wf.line, label: wf.ink },
  }[tone] || { bg: wf.card, border: wf.line, label: wf.ink };
  return (
    <div style={{
      background: colors.bg,
      border: `1px solid ${colors.border}`,
      borderRadius: 10,
      padding: 16,
      minWidth: 0,
    }}>
      <div style={{
        fontFamily: wf.mono,
        fontSize: 10.5,
        letterSpacing: 1,
        textTransform: 'uppercase',
        color: colors.label,
        marginBottom: 10,
      }}>{title}</div>
      <ul style={{ margin: 0, paddingLeft: 18, display: 'grid', gap: 8 }}>
        {items.map((item, i) => (
          <li key={i} style={{ fontFamily: wf.sans, fontSize: 13.5, color: wf.ink2, lineHeight: 1.55 }}>{item}</li>
        ))}
      </ul>
    </div>
  );
};

const EndpointPage = ({ id }) => {
  const ep = ENDPOINTS[id];
  if (!ep) return <div style={{ padding: 40 }}>Unknown endpoint: {id}</div>;
  const code = codeForEndpoint(ep);
  const labHref = `index.html?endpoint=${encodeURIComponent(id)}#playground`;

  // Drive page <title> + <meta description> from endpoint SEO data.
  // Also fires endpoint_docs_viewed with endpoint metadata so the
  // docs→first-API-call funnel is queryable from a single event.
  React.useEffect(() => {
    if (ep.seoTitle) document.title = ep.seoTitle;
    if (ep.seoDescription) {
      let m = document.querySelector('meta[name="description"]');
      if (!m) { m = document.createElement('meta'); m.name = 'description'; document.head.appendChild(m); }
      m.setAttribute('content', ep.seoDescription);
    }
    if (window.MIQAnalytics) {
      window.MIQAnalytics.track('endpoint_docs_viewed', {
        endpoint_id: id, endpoint_group: ep.group, endpoint_path: ep.path,
      });
    }
  }, [id]);

  const onCopy = (text, copyType) => () => {
    try { navigator.clipboard?.writeText(text); } catch (e) {}
    if (window.MIQAnalytics) {
      window.MIQAnalytics.track('endpoint_copy_code_clicked', {
        endpoint_id: id, endpoint_group: ep.group, copy_type: copyType || 'unknown',
      });
    }
  };

  return (
    <Page current="Docs">
      <Breadcrumbs items={[
        { l: 'Docs', href: 'docs.html' },
        { l: ep.group, href: `docs.html#${ep.group}` },
        { l: ep.title },
      ]} />

      {/* Endpoint header */}
      <div style={{ background: wf.card, borderBottom: `1px solid ${wf.line}`, padding: '32px 28px 28px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto', display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 28, alignItems: 'start' }}>
          <div>
            <div style={{ fontFamily: wf.mono, fontSize: 11, letterSpacing: 1.2, color: 'var(--accent)', textTransform: 'uppercase', marginBottom: 10 }}>{ep.group} api</div>
            <h1 style={{ fontFamily: wf.sans, fontSize: 38, fontWeight: 600, letterSpacing: -0.6, margin: 0 }}>{ep.title}</h1>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12 }}>
              <Method kind={ep.method} />
              <span style={{ fontFamily: wf.mono, fontSize: 14, color: wf.ink }}>{ep.path}</span>
              <span onClick={onCopy(`${ep.method} ${ep.path}`, 'endpoint_path')} style={{
                fontFamily: wf.mono, fontSize: 11, color: wf.ink3, cursor: 'pointer',
                padding: '3px 8px', borderRadius: 5, border: `1px solid ${wf.line}`, background: wf.cardAlt,
              }}>copy ⧉</span>
            </div>
            <p style={{ fontFamily: wf.sans, fontSize: 16, color: wf.ink2, lineHeight: 1.6, margin: '18px 0 0', maxWidth: 720 }}>{ep.short}</p>
            <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
              <a href={labHref} style={{ textDecoration: 'none' }}><Btn primary size={14}>Try in Moment Lab</Btn></a>
              <span onClick={onCopy(JSON.stringify(ep.requestExample, null, 2), 'sample_request')} style={{ cursor: 'pointer' }}><Btn size={14}>Copy sample request</Btn></span>
            </div>
          </div>
          <div style={{ background: wf.cardAlt, border: `1px solid ${wf.line}`, borderRadius: 10, padding: 18 }}>
            <div style={{ fontFamily: wf.mono, fontSize: 10.5, letterSpacing: 1, color: wf.ink3, textTransform: 'uppercase' }}>Pricing</div>
            <div style={{ fontFamily: wf.sans, fontSize: 26, fontWeight: 600, marginTop: 4 }}>{priceLabel(id)}</div>
            <div style={{ fontFamily: wf.sans, fontSize: 12, color: wf.ink3, marginTop: 4 }}>No subscription. Estimated cost shown before each run.</div>
            <div style={{ height: 1, background: wf.line, margin: '14px 0' }} />
            <div style={{ fontFamily: wf.mono, fontSize: 10.5, letterSpacing: 1, color: wf.ink3, textTransform: 'uppercase' }}>Auth</div>
            <div style={{ fontFamily: wf.mono, fontSize: 12, color: wf.ink2, marginTop: 6 }}>Authorization: Bearer $MIQ_KEY</div>
            <div style={{ fontFamily: wf.sans, fontSize: 12, color: wf.ink3, marginTop: 4 }}>Same key works on every endpoint.</div>
          </div>
        </div>
      </div>

      <DocsLayout activeId={id}>
        <H2 id="when">When to use it</H2>
        <P>{ep.when}</P>

        <H2 id="what-it-does">What it does</H2>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12, marginBottom: 18 }}>
          <ExplainerCard title="Does" items={ep.does} tone="does" />
          <ExplainerCard title="Does not do" items={ep.doesNot} tone="not" />
          <ExplainerCard title="Good for" items={ep.goodFor} tone="good" />
        </div>

        <H2 id="request">Request parameters</H2>
        <ApiTable rows={ep.params} cols={['Field','Type','Description']} />

        <H2 id="response">Response fields</H2>
        <ApiTable rows={ep.responseFields} cols={['Field','Type','Description']} />

        <H2 id="example">Example</H2>
        <H3>Request body</H3>
        <CodeTabs filename={`${ep.title}.req.json`} tabs={[
          { lang: 'JSON', lines: fmtJson(ep.requestExample, 2).split('\n') },
        ]} />
        <H3>Response</H3>
        <CodeTabs filename={`${ep.title}.res.json`} tabs={[
          { lang: 'JSON', lines: fmtJson(ep.responseExample, 2).split('\n') },
        ]} />

        <H2 id="snippets">Code snippets</H2>
        <CodeTabs filename={`${ep.title}.${ep.method.toLowerCase()}`} tabs={[
          { lang: 'cURL',       lines: code.curl },
          { lang: 'JavaScript', lines: code.js },
          { lang: 'Python',     lines: code.py },
        ]} />

        <H2 id="related">Related endpoints</H2>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {ep.related.map(rid => <RelatedCard key={rid} id={rid} sourceId={id} />)}
        </div>

      </DocsLayout>
    </Page>
  );
};

window.EndpointPage = EndpointPage;
