/* global React, Icon, AnimatedCounter */
// Shared building blocks for product landing pages.

const PStat = ({ n, l }) => (
  <div>
    <div className="counter-num" style={{ fontFamily: 'var(--font-display)', fontSize: 44, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--ink-1)', lineHeight: 1 }}>
      <AnimatedCounter value={n}/>
    </div>
    <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 8 }}>{l}</div>
  </div>
);

const PFeat = ({ num, title, body }) => (
  <div className="card">
    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--accent)', fontWeight: 600, marginBottom: 16 }}>{num}</div>
    <h3 style={{ fontSize: 18, marginBottom: 10 }}>{title}</h3>
    <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink-3)', margin: 0 }}>{body}</p>
  </div>
);

const PStep = ({ n, title, body }) => (
  <div className="card">
    <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--ink-1)', color: '#FFF', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 14, marginBottom: 16 }}>{n}</div>
    <h3 style={{ fontSize: 17, marginBottom: 8 }}>{title}</h3>
    <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink-3)', margin: 0 }}>{body}</p>
  </div>
);

// Generic product page renderer
const ProductLanding = ({ go, accent, iconName, eyebrow, version, h1, lead, mock, stats, featTitle, feats, installSteps, ctaTitle, ctaBody }) => (
  <div className="page-enter">
    <section className="hero" style={{ padding: '80px 0 40px' }}>
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 64, alignItems: 'center' }} className="product-hero-grid">
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
              <div style={{ width: 48, height: 48, borderRadius: 12, background: accent, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#FFF' }}>
                <Icon name={iconName} size={22}/>
              </div>
              <div>
                <div style={{ fontSize: 12, color: 'var(--ink-4)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{eyebrow}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}><span className="chip-mono">{version}</span> &middot; D365 9.2+ &middot; Power Apps</div>
              </div>
            </div>
            <h1 style={{ fontSize: 'clamp(36px, 5vw, 56px)', marginBottom: 20 }}>{h1}</h1>
            <p className="lead" style={{ marginBottom: 28, fontSize: 18 }}>{lead}</p>
            <div className="hero-cta">
              <a className="btn btn-primary btn-lg" href="#" onClick={(e) => { e.preventDefault(); go('contact'); }}>Try it free <Icon name="arrow-right" size={16}/></a>
              <a className="btn btn-secondary btn-lg" href="#install">Install in your tenant</a>
            </div>
          </div>
          <div>{mock}</div>
        </div>
      </div>
    </section>

    <section className="section-tight section-alt">
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 32 }} className="stats-grid">
          {stats.map((s, i) => <PStat key={i} n={s.n} l={s.l}/>)}
        </div>
      </div>
    </section>

    <section className="section">
      <div className="container">
        <span className="eyebrow">What it does</span>
        <h2 style={{ maxWidth: '22ch', marginBottom: 32 }}>{featTitle}</h2>
        <div className="feature-grid">
          {feats.map((f, i) => <PFeat key={i} num={String(i + 1).padStart(2, '0')} title={f.title} body={f.body}/>)}
        </div>
      </div>
    </section>

    <section id="install" className="section section-alt">
      <div className="container">
        <span className="eyebrow">Install</span>
        <h2 style={{ maxWidth: '20ch', marginBottom: 16 }}>Three steps. About one minute.</h2>
        <p className="lead" style={{ maxWidth: '60ch', marginBottom: 32 }}>Sandbox first. Production when you're ready.</p>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }} className="install-grid">
          {installSteps.map((s, i) => <PStep key={i} n={i + 1} title={s.title} body={s.body}/>)}
        </div>
      </div>
    </section>

    <section className="section section-ink">
      <div className="container text-center">
        <h2 style={{ maxWidth: '22ch', margin: '0 auto 16px', fontSize: 'clamp(32px, 4vw, 48px)' }}>{ctaTitle}</h2>
        <p className="lead" style={{ maxWidth: '52ch', margin: '0 auto 32px' }}>{ctaBody}</p>
        <a className="btn btn-primary btn-lg" href="#" onClick={(e) => { e.preventDefault(); go('contact'); }}>Get the trial link <Icon name="arrow-right" size={16}/></a>
      </div>
    </section>
  </div>
);

// ====== KANBAN BOARD MOCK ======
const KanbanMock = () => (
  <div className="browser">
    <div className="browser-bar">
      <span className="browser-dot r"></span><span className="browser-dot y"></span><span className="browser-dot g"></span>
      <div className="browser-url">org.crm.dynamics.com / opportunities / kanban</div>
    </div>
    <div style={{ background: '#FAFAFA', padding: 16, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, minHeight: 320 }}>
      {[
        { title: 'Qualify', count: 4, color: '#0F6CBD', cards: ['Contoso · $48k', 'Fabrikam · $12k', 'Adventure · $89k', 'Northwind · $5k'] },
        { title: 'Propose', count: 2, color: '#A16207', cards: ['Tailwind · $120k', 'Wide World · $34k'] },
        { title: 'Close', count: 1, color: '#15803D', cards: ['Litware · $210k'] },
      ].map((col, i) => (
        <div key={i} style={{ background: '#FFF', borderRadius: 8, padding: 10, border: '1px solid #E5E5E5', display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11, fontWeight: 700, color: col.color, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
            <span>{col.title}</span>
            <span style={{ background: '#F5F5F5', borderRadius: 999, padding: '1px 7px', color: 'var(--ink-3)' }}>{col.count}</span>
          </div>
          {col.cards.map((c, j) => (
            <div key={j} style={{ background: '#FFF', border: '1px solid #E5E5E5', borderLeft: `3px solid ${col.color}`, borderRadius: 6, padding: 10, fontSize: 12, color: 'var(--ink-1)', boxShadow: j === 0 && i === 1 ? '0 4px 12px rgba(0,0,0,0.08)' : 'none', transform: j === 0 && i === 1 ? 'rotate(-1deg)' : 'none' }}>
              <div style={{ fontWeight: 600 }}>{c.split(' · ')[0]}</div>
              <div style={{ color: 'var(--ink-4)', marginTop: 4, fontFamily: 'var(--font-mono)', fontSize: 11 }}>{c.split(' · ')[1]}</div>
            </div>
          ))}
        </div>
      ))}
    </div>
  </div>
);

const KanbanPage = ({ go }) => (
  <ProductLanding
    go={go}
    accent="#0F6CBD"
    iconName="layout-grid"
    eyebrow="Kanban Board"
    version="v1.4.0"
    h1="Drag-and-drop boards for any D365 view."
    lead="Turn any model-driven view into a Kanban board. Group by any choice column, swimlane by owner, drag to update — every move writes back to Dataverse instantly."
    mock={<KanbanMock/>}
    stats={[
      { n: '60s', l: 'Average install time' },
      { n: 'Any', l: 'Choice column as columns' },
      { n: '<100ms', l: 'Drag-to-save latency' },
      { n: '14+', l: 'Languages supported' },
    ]}
    featTitle="Six things that make it feel native."
    feats={[
      { title: 'Bind to any choice column', body: 'Status, stage, priority, custom — pick a choice column and the board renders columns from it. No metadata config.' },
      { title: 'Swimlanes by owner or team', body: 'Toggle a horizontal split by owner, business unit, or any lookup. Useful for stand-ups and load balancing.' },
      { title: 'Drag = write back', body: 'Every drag triggers a Web API update against Dataverse. Honors business rules, security roles, and audit logging.' },
      { title: 'WIP limits', body: 'Cap any column at N records. Once exceeded, the column shows a warning chip and the next drag is rejected with an explainer.' },
      { title: 'Inline filters', body: 'Filter by owner, date range, or any custom view filter. Persists per user — your settings survive a reload.' },
      { title: 'Keyboard friendly', body: 'Tab between cards, space to lift, arrow keys to move, enter to drop. Full accessibility out of the box.' },
    ]}
    installSteps={[
      { title: 'Download solution', body: <>Grab <code>KanbanBoard_managed.zip</code> from your dashboard.</> },
      { title: 'Import to your environment', body: <>Power Platform admin center → Solutions → Import. Pick the <code>.zip</code>.</> },
      { title: 'Add to a view', body: <>Open Form Designer or App Designer, drop <code>KanbanBoard_Control</code> on a section, save & publish.</> },
    ]}
    ctaTitle="Free in your sandbox forever."
    ctaBody="Bundled with Gantt and Video Playlist on paid plans. Try the bundle free in any sandbox environment."
  />
);

// ====== GANTT CHART MOCK ======
const GanttMock = () => (
  <div className="browser">
    <div className="browser-bar">
      <span className="browser-dot r"></span><span className="browser-dot y"></span><span className="browser-dot g"></span>
      <div className="browser-url">org.crm.dynamics.com / projects / Q2-launch</div>
    </div>
    <div style={{ background: '#FFF', padding: 16, minHeight: 320 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '120px repeat(10, 1fr)', gap: 0, fontSize: 11, color: 'var(--ink-4)', fontFamily: 'var(--font-mono)', borderBottom: '1px solid #E5E5E5', paddingBottom: 8, marginBottom: 12 }}>
        <div></div>
        {['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'].map((w) => <div key={w} style={{ textAlign: 'center' }}>{w}</div>)}
      </div>
      {[
        { task: 'Discovery', start: 0, len: 2, color: '#15803D' },
        { task: 'Design', start: 1, len: 3, color: '#15803D' },
        { task: 'Build · API', start: 3, len: 4, color: '#0F6CBD' },
        { task: 'Build · UI', start: 4, len: 3, color: '#0F6CBD' },
        { task: 'QA', start: 6, len: 2, color: '#A16207' },
        { task: 'Launch', start: 8, len: 1, color: '#4F46E5' },
      ].map((bar, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '120px repeat(10, 1fr)', alignItems: 'center', gap: 0, marginBottom: 10, fontSize: 12 }}>
          <div style={{ color: 'var(--ink-2)', fontWeight: 500 }}>{bar.task}</div>
          {Array.from({ length: 10 }).map((_, c) => {
            const inBar = c >= bar.start && c < bar.start + bar.len;
            return (
              <div key={c} style={{ height: 20, paddingRight: 2 }}>
                {inBar && <div style={{ height: '100%', background: bar.color, borderRadius: 3, opacity: 0.85 }}></div>}
              </div>
            );
          })}
        </div>
      ))}
      <div style={{ marginTop: 16, fontSize: 11, color: 'var(--ink-4)', display: 'flex', gap: 16 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, background: '#15803D', borderRadius: 2 }}></span>Discovery</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, background: '#0F6CBD', borderRadius: 2 }}></span>Build</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, background: '#A16207', borderRadius: 2 }}></span>QA</span>
      </div>
    </div>
  </div>
);

const GanttPage = ({ go }) => (
  <ProductLanding
    go={go}
    accent="#15803D"
    iconName="gantt"
    eyebrow="Gantt Chart · Beta"
    version="v0.9.2"
    h1="Project timelines that live inside D365."
    lead="Plot tasks against time with dependencies, drag-resize, and weekend awareness. Bound to any entity with a start/end date — projects, sprints, campaigns, manufacturing runs."
    mock={<GanttMock/>}
    stats={[
      { n: 'Any', l: 'Entity with two dates' },
      { n: '6', l: 'Dependency types' },
      { n: '∞', l: 'Tasks per chart' },
      { n: '✓', l: 'Print-clean export' },
    ]}
    featTitle="Project planning, the way Microsoft would build it."
    feats={[
      { title: 'Drag-resize bars', body: 'Grab either edge to change start or end. Grab the middle to slide the whole task. Every change writes back via Web API.' },
      { title: 'Smart dependencies', body: 'FS, SS, FF, SF — all four dependency types, with auto-shift on the dependent when you move a predecessor.' },
      { title: 'Weekend awareness', body: 'Configurable working days and company holidays. Bars skip non-working days; durations reflect actual work time.' },
      { title: 'Critical path', body: 'One toggle highlights the longest dependency chain. Useful for triage when a deadline starts slipping.' },
      { title: 'Zoom levels', body: 'Day, week, month, quarter, year. Smooth zoom transitions; the bar widths recalc, the label density adapts.' },
      { title: 'Print-clean PDF', body: 'A landscape A3 export that does not look like 2008. Page-break aware, header repeats per page, fits any modern printer.' },
    ]}
    installSteps={[
      { title: 'Download solution', body: <>Grab <code>GanttChart_managed.zip</code> from your dashboard.</> },
      { title: 'Import to your environment', body: <>Power Platform admin center → Solutions → Import. Pick the <code>.zip</code>.</> },
      { title: 'Bind to your entity', body: <>Open Form Designer, drop <code>GanttChart_Control</code> on a section, point it at your start/end date columns.</> },
    ]}
    ctaTitle="Beta is open. Sign up to break it."
    ctaBody="Free during beta. Help us shake out the edges and we'll thank you in the v1 release notes."
  />
);

// ====== VIDEO PLAYLIST MOCK ======
const VideoMock = () => (
  <div className="browser">
    <div className="browser-bar">
      <span className="browser-dot r"></span><span className="browser-dot y"></span><span className="browser-dot g"></span>
      <div className="browser-url">org.crm.dynamics.com / training / new-hire</div>
    </div>
    <div style={{ background: '#FAFAFA', padding: 16, display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 12, minHeight: 320 }}>
      <div style={{ background: '#0A0A0A', borderRadius: 8, position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(135deg, #1F2937 0%, #0A0A0A 100%)' }}></div>
        <div style={{ position: 'relative', width: 56, height: 56, borderRadius: 999, background: 'rgba(255,255,255,0.95)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ width: 0, height: 0, borderLeft: '14px solid #0A0A0A', borderTop: '9px solid transparent', borderBottom: '9px solid transparent', marginLeft: 4 }}></div>
        </div>
        <div style={{ position: 'absolute', bottom: 12, left: 12, right: 12, color: '#FFF' }}>
          <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 6 }}>Module 2 · Logging cases in D365</div>
          <div style={{ height: 3, background: 'rgba(255,255,255,0.2)', borderRadius: 2, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: '34%', background: '#FFF' }}></div>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'rgba(255,255,255,0.7)', marginTop: 4, fontFamily: 'var(--font-mono)' }}>
            <span>2:14</span><span>6:32</span>
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 4 }}>Playlist · 5 of 8</div>
        {[
          { t: 'Welcome', d: '1:42', done: true, active: false },
          { t: 'D365 navigation', d: '4:18', done: true, active: false },
          { t: 'Logging cases', d: '6:32', done: false, active: true },
          { t: 'Resolving cases', d: '5:21', done: false, active: false },
          { t: 'Reporting', d: '7:55', done: false, active: false },
        ].map((it, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 8px', borderRadius: 5, background: it.active ? '#FFF' : 'transparent', border: it.active ? '1px solid #0A0A0A' : '1px solid transparent', fontSize: 11 }}>
            <div style={{ width: 16, height: 16, borderRadius: 999, background: it.done ? '#15803D' : '#E5E5E5', color: '#FFF', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 9, flexShrink: 0 }}>
              {it.done ? '✓' : i + 1}
            </div>
            <div style={{ flex: 1, color: 'var(--ink-1)', fontWeight: it.active ? 600 : 400 }}>{it.t}</div>
            <div style={{ color: 'var(--ink-4)', fontFamily: 'var(--font-mono)', fontSize: 10 }}>{it.d}</div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

const VideoPage = ({ go }) => (
  <ProductLanding
    go={go}
    accent="#0A0A0A"
    iconName="video"
    eyebrow="Video Playlist Control"
    version="v1.2.0"
    h1="Training videos, right inside the form."
    lead="Embed a sequenced playlist of videos directly inside any model-driven app form. Track who watched what, gate completion on viewing, and drop the LMS tab altogether."
    mock={<VideoMock/>}
    stats={[
      { n: '2.4×', l: 'Faster first-ticket close' },
      { n: 'Per-user', l: 'Watch progress saved' },
      { n: 'YouTube,', l: 'Vimeo, MP4, Stream' },
      { n: '0', l: 'Tabs to switch' },
    ]}
    featTitle="The training video, where the work actually happens."
    feats={[
      { title: 'Bind to any entity', body: 'Attach a playlist to a record, a record type, or a user role. Different playlists for different teams, no code.' },
      { title: 'Per-user progress', body: 'Each user\'s watch progress is saved per video and per playlist. Resume right where they left off, on any device.' },
      { title: 'Completion gating', body: 'Optionally lock a form action behind playlist completion. New hires cannot resolve cases until they have watched the SOP video.' },
      { title: 'Multi-source', body: 'YouTube, Vimeo, Microsoft Stream, raw MP4, and SharePoint links all play in the same shell. Mix and match in one playlist.' },
      { title: 'Captions and transcripts', body: 'WebVTT captions render natively. Transcripts surface as a side panel and are searchable across the playlist.' },
      { title: 'Reporting', body: 'A built-in dashboard entity tracks watch time per user, per video, per role. Drop into any Power BI report.' },
    ]}
    installSteps={[
      { title: 'Download solution', body: <>Grab <code>VideoPlaylist_managed.zip</code> from your dashboard.</> },
      { title: 'Import to your environment', body: <>Power Platform admin center → Solutions → Import. Pick the <code>.zip</code>.</> },
      { title: 'Add to a form', body: <>Open Form Designer, drop <code>VideoPlaylist_Control</code> on a section, point it at your video list table.</> },
    ]}
    ctaTitle="Onboard new hires faster."
    ctaBody="Customers report a 2.4× reduction in time-to-first-resolved-case once training lives inside the form, not in a separate LMS."
  />
);

window.KanbanPage = KanbanPage;
window.GanttPage = GanttPage;
window.VideoPage = VideoPage;
