const { Page, H2, H3, P, Rules, Code, Tok, Callout, Example, DoDont, TokenTable, ContrastRow, TokenList } = window.DocsKit;
const DSF = window.Ds7NOWDesignSystem_cb8d5f;

function OverviewPage({ go }) {
  const tiles = [
    ['foundations/tokens', 'Design tokens', 'Primitive, basic and interface tokens, and when to use each tier.'],
    ['foundations/color', 'Color', 'Brand greens, accents, neutrals and the roles they play in the interface.'],
    ['foundations/typography', 'Typography', 'Right Grotesk for display, Basis Grotesque Pro for everything else.'],
    ['foundations/spacing', 'Spacing & layout', 'The 4px-based scale, containers, gutters and breakpoints.'],
    ['content/voice', 'Voice & tone', 'Short, friendly, numbers up front. How 7NOW copy is written.'],
    ['components/button', 'Components', 'Eight components built from the 7now.com stylesheet.'],
  ];
  return (
    <Page eyebrow="7NOW Design System" title="Build 7NOW experiences that feel fast" lead="Tokens, components and guidelines for 7-Eleven's on-demand delivery brand, taken from the live 7now.com site. Use them to build web screens, prototypes and marketing pages that match production.">
      <div className="doc-tiles">{tiles.map(([r, t, d]) => <a key={r} className="doc-tile" href={'#/' + r}><strong>{t}</strong><span>{d}</span></a>)}</div>
      <H2>Principles</H2>
      <div className="doc-principles">
        <div><h3>Convenience first</h3><p>Every screen gets the customer to an address field or a product quickly. The hero is an address form and nothing else.</p></div>
        <div><h3>Green is the brand, black is the action</h3><p>7-Eleven green marks the brand and promotions. Main calls to action are black pills.</p></div>
        <div><h3>Pills for actions, 8px for containers</h3><p>Buttons and badges are fully rounded. Cards and fields use an 8px radius. Nothing else gets rounded.</p></div>
      </div>
      <H2>Get started</H2>
      <P>Link one stylesheet. It brings in every token, the body defaults and the component classes.</P>
      <Code>{`<link rel="stylesheet" href="styles.css">

<!-- plain HTML -->
<button class="btn btn--primary">Go</button>

<!-- or React, from the compiled bundle -->
const { Button } = window.Ds7NOWDesignSystem_cb8d5f;
<Button>Go</Button>`}</Code>
      <Callout kind="warn" title="Fonts">Basis Grotesque Pro and Right Grotesk are licensed fonts and aren't included. Until they're added, pages use self-hosted Hanken Grotesk and Schibsted Grotesk stand-ins.</Callout>
    </Page>
  );
}

function TokensPage() {
  const [tier, setTier] = React.useState('interface');
  const [q, setQ] = React.useState('');
  const re = q ? new RegExp(q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i') : null;
  return (
    <Page eyebrow="Foundations" title="Design tokens" lead="Tokens are named design decisions. 7NOW tokens come in three tiers, and each tier only references the tier below it.">
      <div className="doc-tiers">
        <div><span className="doc-tier doc-tier--primitive">1 · Primitive</span><Tok>--green-700</Tok><p>Raw values: the palette, the spacing and type scales, motion. Basic and interface tokens reference them. Use them directly when no role fits.</p></div>
        <div><span className="doc-tier doc-tier--basic">2 · Basic</span><Tok>--green-dark</Tok><p>Global roles with plain names: <Tok>--bg</Tok>, <Tok>--text</Tok>, <Tok>--border</Tok>, <Tok>--warning</Tok>. Use them when no interface token fits.</p></div>
        <div><span className="doc-tier doc-tier--interface">3 · Interface</span><Tok>--button-bg-brand</Tok><p>Component tokens. Start here. Components use these, so a change here updates every component that uses the role.</p></div>
      </div>
      <H2>How to choose</H2>
      <Rules items={[
        <>Look for an interface token first: <Tok>--button-bg-primary</Tok>, <Tok>--card-padding</Tok>, <Tok>--input-radius</Tok>.</>,
        <>If no interface token fits, use a basic role such as <Tok>--text-secondary</Tok> or <Tok>--green-pale</Tok>.</>,
        <>If no role fits, use a primitive scale value such as <Tok>--space-24</Tok>. If you need it often, propose a new interface token.</>,
        'Never hard-code a hex, pixel or shadow value that already exists as a token.',
      ]} />
      <H2>Naming</H2>
      <Code>{`--{component}-{property}-{variant}-{state}

--button-bg-primary-hover
--title-md-size
--button-padding-x-sm
--card-radius`}</Code>
      <H2>All tokens</H2>
      <div className="doc-toolbar">
        <div className="doc-seg">{['interface', 'basic', 'primitive'].map(t => <button key={t} className={tier === t ? 'is-on' : ''} onClick={() => setTier(t)}>{t}</button>)}</div>
        <input className="doc-filter" placeholder="Filter tokens" value={q} onChange={e => setQ(e.target.value)} />
      </div>
      <TokenTable tier={tier} match={re} />
    </Page>
  );
}

function ColorPage() {
  const groups = [
    ['Brand greens', /^--green/], ['Accents', /^--(red|orange|yellow|brown|blue|navy|error)/], ['Neutrals', /^--(white|gray|silver|coolgray|ink|black|overlay)/],
  ];
  return (
    <Page eyebrow="Foundations" title="Color" lead="7-Eleven green anchors the brand. Black carries the main actions. Neutrals do most of the work, and accents are reserved for deals and status.">
      <H2>Usage rules</H2>
      <Rules items={[
        <>Use <strong>green</strong> (<Tok>--green</Tok> #007350) for brand moments: the category band, the app button, success states and links.</>,
        <>Use <strong>black</strong> (<Tok>--button-bg-primary</Tok>) for the main action on a screen. One main action per view.</>,
        <>Use <strong>7-Eleven red</strong> #EC0F2A and <strong>orange</strong> #FF6C00 sparingly, for accents and highlights. Don't use red for errors; use <Tok>--error</Tok> #D93235.</>,
        <><strong>Yellow</strong> (<Tok>--badge-bg-promo</Tok>) is only for deals and promotions. <strong>Gold</strong> (yellow-light + brown) is for 7Rewards membership.</>,
        'Body text is ink #111. Headings, cards and fields use pure black.',
        'Never use gradients. Sections change with flat colour bands.',
      ]} />
      <DoDont
        doEl={<div style={{ display: 'flex', gap: 8 }}><DSF.Button>Go</DSF.Button><DSF.Button variant="secondary">Sign in</DSF.Button></div>}
        doText="use one black primary action, supported by secondary buttons."
        dontEl={<div style={{ display: 'flex', gap: 8 }}><DSF.Button variant="brand">Go</DSF.Button><DSF.Button variant="brand">Sign in</DSF.Button></div>}
        dontText="put several green buttons side by side. Green is for the app button and brand moments." />
      <H2>Roles</H2>
      <H3>Text</H3><TokenTable tier="basic" match={/^--(text|icon)/} />
      <H3>Backgrounds</H3><TokenTable tier="basic" match={/^--bg/} />
      <H3>Borders & focus</H3><TokenTable tier="basic" match={/^--(border|focus)/} />
      <H3>Buttons</H3><TokenTable tier="interface" match={/^--button-/} />
      <H3>Badges</H3><TokenTable tier="interface" match={/^--badge-/} />
      <H2>Accessible pairings</H2>
      <P>Body text needs at least 4.5:1 contrast. Large display text (24px and up) needs at least 3:1. Ratios below are calculated live from the tokens.</P>
      <div className="doc-table-wrap"><table className="doc-table">
        <thead><tr><th>Sample</th><th>Foreground</th><th>Background</th><th>Ratio</th><th>WCAG</th></tr></thead>
        <tbody>
          <ContrastRow fg="--text" bg="--bg" label="Body text" />
          <ContrastRow fg="--text-secondary" bg="--bg" label="Secondary" />
          <ContrastRow fg="--text-placeholder" bg="--bg" label="Placeholder" />
          <ContrastRow fg="--link" bg="--bg" label="Link" />
          <ContrastRow fg="--button-text-primary" bg="--button-bg-primary" label="Go" />
          <ContrastRow fg="--button-text-brand" bg="--button-bg-brand" label="Get the App" />
          <ContrastRow fg="--badge-text-promo" bg="--badge-bg-promo" label="$0 Delivery" />
          <ContrastRow fg="--badge-text-gold" bg="--badge-bg-gold" label="Gold Pass" />
          <ContrastRow fg="--badge-text-success" bg="--badge-bg-success" label="In stock" />
          <ContrastRow fg="--badge-text-info" bg="--badge-bg-info" label="New" />
          <ContrastRow fg="--badge-text-error" bg="--badge-bg-error" label="Sold out" />
          <ContrastRow fg="--text-inverse" bg="--bg-inverse" label="Footer" />
        </tbody>
      </table></div>
      <H2>Palette</H2>
      {groups.map(([t, re]) => <React.Fragment key={t}><H3>{t}</H3><TokenTable tier="basic" match={re} /></React.Fragment>)}
    </Page>
  );
}

function TypographyPage() {
  const roles = [
    ['display', 'What are you craving?', 'Right Grotesk Bold', '32/36 · 56/64 at 768px', 'Hero and section headlines', 'var(--font-display)', 700],
    ['title-lg', 'Hungry?', 'Basis Bold', '32/36', 'Content card titles', 'var(--font-heading)', 700],
    ['title-md', 'Frequently asked questions', 'Basis Bold', '28/32', 'Utility section headings; stat figures use Right Grotesk', 'var(--font-heading)', 700],
    ['title-sm', 'How can we help?', 'Basis Bold', '18/24', 'Footer column headings', 'var(--font-heading)', 700],
    ['body-lg', 'How does delivery work with 7NOW?', 'Basis Semibold', '18/28', 'FAQ questions, stat captions', 'var(--font-body)', 600],
    ['body', '7-Eleven has a wide selection of fresh grab-and-go options.', 'Basis Regular', '16/22, −0.1px', 'Default body copy', 'var(--font-body)', 400],
    ['action', 'Get Food', 'Basis Semibold/Bold', '16/24', 'Button labels', 'var(--font-body)', 600],
    ['label', 'Leave Feedback', 'Basis Medium', '14/20', 'Small buttons, field labels, footer links, category names', 'var(--font-body)', 500],
    ['caption', 'This site is intended for residents of the U.S.', 'Basis Regular', '12/16', 'Badges, helper text, fine print', 'var(--font-body)', 400],
  ];
  return (
    <Page eyebrow="Foundations" title="Typography" lead="Two typefaces. Right Grotesk gives headlines their loud, compact voice. Basis Grotesque Pro does everything else.">
      <H2>Typefaces</H2>
      <div className="doc-faces">
        <div><span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 56, lineHeight: 1 }}>Aa</span><strong>Right Grotesk</strong><p>Bold for display headlines and stat figures. Black for the wordmark only. <Tok>--font-display</Tok></p></div>
        <div><span style={{ fontFamily: 'var(--font-body)', fontSize: 56, lineHeight: 1 }}>Aa</span><strong>Basis Grotesque Pro</strong><p>Regular, Medium, Semibold and Bold for titles, body, labels and UI. <Tok>--font-body</Tok></p></div>
      </div>
      <H2>Type roles</H2>
      <P>Use the <Tok>--{'{role}'}-size</Tok> and <Tok>--{'{role}'}-leading</Tok> pair together. Don't mix the size of one role with the line height of another.</P>
      <div className="doc-typeroles">{roles.map(([k, s, face, metric, use, fam, w]) => (
        <div key={k} className="doc-typerole">
          <div className="doc-typerole__meta"><Tok>{k}</Tok><span>{face}</span><span>{metric}</span><span className="doc-muted">{use}</span></div>
          <div style={{ fontFamily: fam, fontWeight: w, fontSize: `var(--type-${k}-size${k === 'display' ? '-lg' : ''})`, lineHeight: `var(--type-${k}-leading${k === 'display' ? '-lg' : ''})`, minWidth: 0 }}>{s}</div>
        </div>))}
      </div>
      <H2>Rules</H2>
      <Rules items={[
        'Use Right Grotesk only for display headlines and stat figures. Never use it for body copy, buttons or labels.',
        'Use sentence case for headings and FAQ questions. Use Title Case for buttons, links and stat titles.',
        'Centre section headlines. Left-align long-form copy such as FAQ answers.',
        'Don\'t go below 12px. Body copy is 16px.',
        'Body copy tracks at −0.1px. Buttons and the footer use 0.',
      ]} />
      <DoDont
        doEl={<div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 32, lineHeight: '36px', textAlign: 'center' }}>What are you craving?</div>}
        doText="use a short, sentence-case question in Right Grotesk."
        dontEl={<div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18, lineHeight: '24px' }}>7NOW offers delivery in over 50 major cities and metroplexes, and the list keeps expanding.</div>}
        dontText="set paragraphs or small text in Right Grotesk." />
      <H2>Type scale</H2>
      <TokenTable tier="primitive" match={/^--(font-size|line-height|weight|letter-spacing)/} />
    </Page>
  );
}

function SpacingPage() {
  return (
    <Page eyebrow="Foundations" title="Spacing & layout" lead="Spacing follows Tailwind's 4px steps. Basic roles describe what the space is for (a gap, a card inset, a section), so layouts stay consistent.">
      <H2>Rules</H2>
      <Rules items={[
        <>Use gap roles for space between siblings: <Tok>--gap-xs</Tok> 4 · <Tok>sm</Tok> 8 · <Tok>md</Tok> 12 · <Tok>lg</Tok> 16 · <Tok>xl</Tok> 24.</>,
        <>Use inset roles for padding inside components: cards 24, fields 20 (40 with an icon), FAQ rows 16 × 24.</>,
        <>Sections are 32px tall bands on mobile (<Tok>--section-sm</Tok>) and 64px on desktop (<Tok>--section-lg</Tok>).</>,
        <>The page gutter is 16px, rising to 48px in the footer at 1024px and up.</>,
        'Centre content in a container. Never let text run the full width of a large screen.',
      ]} />
      <H2>Interface spacing</H2><TokenTable tier="interface" match={/^--.*-(padding|gap|offset)/} preview="space" />
      <H2>Basic roles</H2><TokenTable tier="basic" match={/^--(gap|page-gutter|section)/} preview="space" />
      <H2>Primitive scale</H2><TokenTable tier="primitive" match={/^--space/} preview="space" />
      <H2>Containers</H2>
      <div className="doc-table-wrap"><table className="doc-table"><thead><tr><th>Token</th><th>Width</th><th>Use</th></tr></thead><tbody>
        {[['--container-sm', '343px', 'Hero form (mobile), stat column'], ['--container-md', '548px', 'Hero form (768px and up)'], ['--container-4xl', '56rem / 896px', 'FAQ, banners'], ['--container-6xl', '72rem / 1152px', 'Stats, city lists'], ['--container-7xl', '80rem / 1280px', 'Card rows'], ['--container-footer', '137.5rem', 'Footer']].map(r => <tr key={r[0]}><td><Tok>{r[0]}</Tok></td><td className="doc-mono">{r[1]}</td><td>{r[2]}</td></tr>)}
      </tbody></table></div>
      <H2>Breakpoints</H2>
      <P>Mobile first, using Tailwind's defaults. CSS can't read custom properties inside media queries, so write the value and name the token in a comment.</P>
      <Code>{`@media (min-width: 48rem) { /* --breakpoint-md */ … }

--breakpoint-sm  40rem  640px
--breakpoint-md  48rem  768px   display type steps up, header "Get the App" hides
--breakpoint-lg  64rem  1024px  footer gutter 48px
--breakpoint-xl  80rem  1280px
--breakpoint-2xl 96rem  1536px`}</Code>
      <H2>Control sizes</H2><TokenTable match={/^--(control-|icon-size|button-height|input-height)/} preview="size" />
    </Page>
  );
}

function ShapePage() {
  return (
    <Page eyebrow="Foundations" title="Shape & elevation" lead="Few radii and few shadows. Pills for actions, 8px for containers, and shadow only on cards and raised buttons.">
      <H2>Radius</H2>
      <Rules items={[
        <>Buttons and badges are always pills: <Tok>--button-radius</Tok>, <Tok>--badge-radius</Tok>.</>,
        <>Cards and fields use 8px: <Tok>--card-radius</Tok>, <Tok>--input-radius</Tok>.</>,
        <>Category bubbles are circles: <Tok>--card-radius-bubble</Tok>.</>,
        'Don\'t round images inside cards separately. The card clips them.',
      ]} />
      <TokenTable match={/radius/} preview="radius" />
      <H2>Elevation</H2>
      <Rules items={[
        <>Content cards sit on <Tok>--card-shadow</Tok> (md) and lift to <Tok>--card-shadow-hover</Tok> (lg) when they're interactive.</>,
        <>Buttons inside content are raised with <Tok>--button-shadow</Tok>.</>,
        'Shadows are 10% black. No coloured, inner or blurred-glass shadows.',
        'Stat and category cards are flat: no surface, no shadow.',
      ]} />
      <TokenTable match={/shadow/} preview="shadow" />
      <H2>Borders</H2>
      <P>Borders are 1px hairlines in very light greys. Focus uses a 2px black ring with a 2px offset, or a white ring on dark surfaces.</P>
      <TokenTable match={/^--(border-width|ring)/} />
    </Page>
  );
}

function MotionPage() {
  return (
    <Page eyebrow="Foundations" title="Motion" lead="Motion is short and functional: colour and shadow transitions, a press scale and a chevron flip. No bounces, no entrance animations.">
      <Rules items={[
        <><Tok>--transition-ui</Tok> (150ms) for hovers, borders and background changes.</>,
        <><Tok>--transition-action</Tok> (200ms) for buttons and links that act as buttons.</>,
        <>Buttons scale to <Tok>--scale-press</Tok> (.95) while pressed.</>,
        <>Accordion chevrons rotate <Tok>--rotate-flip</Tok> (180°) when open.</>,
        'All motion uses the standard ease, cubic-bezier(.4, 0, .2, 1).',
      ]} />
      <Example title="Hover and press the buttons" code={`<Button>Go</Button>\n<Button elevated>Get Food</Button>`}>
        <div style={{ display: 'flex', gap: 12 }}><DSF.Button>Go</DSF.Button><DSF.Button elevated>Get Food</DSF.Button><DSF.Button variant="secondary">Sign in</DSF.Button></div>
      </Example>
      <TokenTable match={/^--(duration|ease|scale|rotate|transition|opacity)/} />
    </Page>
  );
}

function IconsPage() {
  return (
    <Page eyebrow="Foundations" title="Iconography" lead="7NOW uses very few icons. They are simple outline glyphs that support the text and never replace it.">
      <div className="doc-icons">{['chevron-down', 'map-pin', 'search'].map(n => <div key={n}><img src={`../assets/icons/${n}.svg`} width="28" height="28" alt="" /><Tok>{n}</Tok></div>)}</div>
      <H2>Rules</H2>
      <Rules items={[
        '24px viewBox, 2px stroke, round caps and joins, no fill. Colour comes from currentColor.',
        <>Show at 20px (<Tok>--icon-size</Tok>) in <Tok>--icon</Tok>, or inherit the text colour.</>,
        'Icons sit inside fields (pin, search) and controls (the accordion chevron). Buttons are text only.',
        'If you need more icons, use an outline set with the same 2px stroke. Mark it as a substitution.',
        'Category and stat imagery are full-colour illustrations, not icons.',
        'No emoji, and no unicode characters as icons.',
      ]} />
      <Callout kind="info" title="Not included">The App Store and Google Play badges and social icons are official artwork that isn't bundled. Components show placeholders until you supply the files.</Callout>
    </Page>
  );
}

function VoicePage() {
  return (
    <Page eyebrow="Content" title="Voice & tone" lead="Friendly, quick and to the point. 7NOW talks like a helpful store clerk who knows you're in a hurry.">
      <H2>Principles</H2>
      <div className="doc-principles">
        <div><h3>Speak to “you”</h3><p>Address the customer directly. Refer to the brand in the third person as 7NOW or 7-Eleven.</p></div>
        <div><h3>Lead with numbers</h3><p>“30 Minutes”, “24/7”, “$0 Delivery”, “over 20,000 products”. Use numerals and symbols.</p></div>
        <div><h3>A little playful</h3><p>Support copy can have a light touch: “perfect for 2AM munchies”. FAQ and legal copy stays plain and complete.</p></div>
      </div>
      <H2>Casing</H2>
      <div className="doc-table-wrap"><table className="doc-table"><thead><tr><th>Element</th><th>Case</th><th>Example</th></tr></thead><tbody>
        {[['Buttons and CTAs', 'Title Case, verb first, 1–2 words', 'Go · Sign in · Get the App · Get Food'], ['Section headings', 'Sentence case, often a question', 'What are you craving? · Frequently asked questions'], ['Card titles', 'One word plus a question mark', 'Hungry? · Thirsty? · Stock up?'], ['Stat titles', 'Title Case with numerals', '2 Million+ · 30 Minutes · 24/7 Delivery'], ['FAQ questions', 'Sentence case', 'How fast are 7NOW deliveries?'], ['Footer links', 'Title Case', 'Leave Feedback · Contact Us']].map(r => <tr key={r[0]}><td>{r[0]}</td><td>{r[1]}</td><td>{r[2]}</td></tr>)}
      </tbody></table></div>
      <H2>Names</H2>
      <Rules items={['Always 7NOW, in capitals and with no space.', 'Always 7-Eleven, with a hyphen.', 'Always 7Rewards, as one word.']} />
      <H2>Examples</H2>
      <DoDont doEl={<DSF.Button elevated>Get Drinks</DSF.Button>} doText="write a short CTA that starts with a verb."
        dontEl={<DSF.Button elevated>Click here to browse our drinks</DSF.Button>} dontText="write long CTAs or use “click here”." />
      <DoDont doEl={<p className="doc-p" style={{ margin: 0 }}>The average delivery time is 27 minutes.</p>} doText="state facts plainly with numerals."
        dontEl={<p className="doc-p" style={{ margin: 0 }}>Super-fast deliveries! 🚀🚀</p>} dontText="use emoji or stacked exclamation marks." />
    </Page>
  );
}

Object.assign(window, { DocsFoundations: { OverviewPage, TokensPage, ColorPage, TypographyPage, SpacingPage, ShapePage, MotionPage, IconsPage, VoicePage } });
