/* global React, Icon, BrandIcon, D365Mock, BrowserShot, Photo, STOCK, SHOTS */
const HomePage = ({ go }) => {
  return (
    <div className="page-enter">
      {/* Hero */}
      <section className="hero">
        <div className="grid-bg" style={{ position: 'absolute', inset: 0, opacity: 0.6, maskImage: 'linear-gradient(to bottom, black 20%, transparent 100%)', WebkitMaskImage: 'linear-gradient(to bottom, black 20%, transparent 100%)' }}></div>
        <div className="container" style={{ position: 'relative' }}>
          <span className="chip" style={{ marginBottom: 24 }}><Icon name="zap" size={14}/> A Microsoft Power Platform partner</span>
          <h1>The full <span className="hl">Power Platform</span> team you don't have to hire.</h1>
          <p className="lead">Dynamics 365, Power Apps, AI Builder, Power Automate, Copilot Studio, code apps, PCF — we design, build, and ship across the entire Microsoft business stack. Plus a growing line of our own productivity products.</p>
          <div className="hero-cta">
            <a className="btn btn-primary btn-lg" href="#" onClick={(e) => { e.preventDefault(); go('contact'); }}>Talk to us <Icon name="arrow-right" size={16}/></a>
            <a className="btn btn-secondary btn-lg" href="#services">What we do</a>
          </div>
          <div style={{ marginTop: 56 }}>
            <BrowserShot
              src={SHOTS.aiAssistant}
              url="org.crm.dynamics.com / opportunities / Café BG-1 Grinder for Alpine Ski House"
              alt="Smart Panel AI inside a Dynamics 365 record"
              fallback={<D365Mock/>}
            />
          </div>
        </div>
      </section>

      {/* Logos — auto-scrolling marquee */}
      <section className="section-tight section-alt">
        <div className="container">
          <div className="small text-center muted" style={{ marginBottom: 24, fontWeight: 500 }}>Building on the Microsoft stack since day one</div>
        </div>
        <div className="marquee">
          <div className="marquee-track">
            {[
              'Dynamics 365', 'Power Apps', 'Power Automate', 'AI Builder', 'Copilot Studio',
              'Azure OpenAI', 'Dataverse', 'Power BI', 'Power Pages', 'SharePoint', 'Microsoft Teams',
              // duplicate for seamless loop
              'Dynamics 365', 'Power Apps', 'Power Automate', 'AI Builder', 'Copilot Studio',
              'Azure OpenAI', 'Dataverse', 'Power BI', 'Power Pages', 'SharePoint', 'Microsoft Teams',
            ].map((name, i) => (
              <React.Fragment key={i}>
                <span className="marquee-item">{name}</span>
                <span className="marquee-dot"/>
              </React.Fragment>
            ))}
          </div>
        </div>
      </section>

      {/* Services — what we do */}
      <section id="services" className="section">
        <div className="container">
          <span className="eyebrow">What we do</span>
          <h2 style={{ maxWidth: '22ch', marginBottom: 16 }}>End-to-end services across the Microsoft business stack.</h2>
          <p className="lead" style={{ maxWidth: '62ch', marginBottom: 48 }}>Whether you need a single PCF control, a custom model-driven app, or a full Copilot rollout — we have shipped it. The list below is a starting point, not a ceiling.</p>

          <div className="feature-grid">
            <ServiceCard brand="d365"           title="Dynamics 365 customization" body="Sales, Customer Service, Field Service, Project Operations. Custom entities, business rules, plugins, workflows, ribbon, sitemap, security."/>
            <ServiceCard brand="power-apps"     title="Power Apps development"     body="Model-driven and canvas apps. From a quick internal tool to multi-environment ALM with managed solutions and pipelines."/>
            <ServiceCard brand="copilot"        title="AI & Microsoft Copilot"     body="AI Builder models, Copilot Studio agents, custom GPTs over Dataverse, RAG over SharePoint, prompt engineering for D365 forms."/>
            <ServiceCard brand="power-automate" title="Power Automate workflows"   body="Cloud flows, desktop flows, business process flows, RPA. Approvals, integrations, scheduled jobs, event-driven automations."/>
            <ServiceCard brand="ai-agents"      title="AI agents on your data"     body="Autonomous agents that read Dataverse, take actions, hand off to humans. Built on Copilot Studio + Azure OpenAI."/>
            <ServiceCard brand="azure"          title="Azure-hosted code apps"     body="Pro-code Azure-hosted apps when low-code hits a wall. Functions, App Service, Static Web Apps, Logic Apps, Event Grid."/>
            <ServiceCard brand="pcf"            title="PCF controls (custom)"      body="Need a control that does not exist? We build PCF controls from scratch — drag-drop, charts, data grids, signature pads, you name it."/>
            <ServiceCard brand="power-bi"       title="Power BI &amp; reporting"   body="Embedded reports, paginated dashboards, dataflows. Plug Power BI into D365 forms or roll up KPIs across environments."/>
          </div>
        </div>
      </section>

      {/* Products */}
      <section className="section section-alt">
        <div className="container">
          <span className="eyebrow">Our products</span>
          <h2 style={{ maxWidth: '22ch', marginBottom: 16 }}>Productivity controls we sell to the world.</h2>
          <p className="lead" style={{ maxWidth: '62ch', marginBottom: 40 }}>Ready-to-install solutions packaged from problems we solved for our own customers. New ones ship every quarter.</p>

          <div className="feature-grid">
            <ProductCard accent="#4F46E5" iconName="sparkles" name="Smart Panel AI" desc="An AI side panel that summarizes records, drafts replies, and answers questions inside D365." status="Live" version="v2.1" badge="AI" go={go}/>
            <ProductCard accent="#0F6CBD" iconName="layout-grid" name="Kanban Board" desc="Turn any model-driven view into a drag-and-drop Kanban. Group by any choice column." status="Live" version="v1.4" go={go}/>
            <ProductCard accent="#0A0A0A" iconName="video" name="Video Playlist" desc="Embed a sequenced playlist of training videos directly inside a D365 form." status="Live" version="v1.2" go={go}/>
            <ProductCard accent="#15803D" iconName="gantt" name="Gantt Chart" desc="Plot project tasks against time with dependencies, drag-resize, and weekend awareness." status="Beta" version="v0.9" go={go}/>
          </div>
          <div style={{ marginTop: 32, fontSize: 13, color: 'var(--ink-4)', fontStyle: 'italic' }}>And more on the way — every quarter.</div>
        </div>
      </section>

      {/* Why */}
      <section className="section">
        <div className="container">
          <span className="eyebrow">Why teams pick Dynawins</span>
          <h2 style={{ maxWidth: '20ch', marginBottom: 32 }}>Microsoft-native by default. Practical by habit.</h2>
          <div className="feature-grid">
            <FeatureBlock iconName="users" title="Microsoft-only specialists" body="We do not chase every framework. Dynamics 365, Power Platform, Azure — that is the entire menu, and we go deep."/>
            <FeatureBlock iconName="zap" title="Ship in weeks, not quarters" body="Most engagements move from kickoff to a working pilot inside 2–4 weeks. Then iterate fast based on real usage."/>
            <FeatureBlock iconName="lock" title="Stays in your tenant" body="Everything we build runs in your Azure / Dataverse subscription. Your data never leaves your boundary."/>
            <FeatureBlock iconName="panel-right" title="Native UX, every time" body="Looks and feels like Microsoft. Respects your theme, language, business units, and security roles."/>
            <FeatureBlock iconName="clock" title="Documented, not magic" body="Every solution we ship comes with an architecture doc, a deployment runbook, and a handoff session for your admin."/>
            <FeatureBlock iconName="shield" title="Co-sell partner" body="We work with Microsoft Partner managers on co-sell deals — joint case studies, MACC retirement, partner pricing on Azure."/>
          </div>
        </div>
      </section>

      {/* Testimonials */}
      <section className="section section-alt">
        <div className="container">
          <span className="eyebrow">What teams say</span>
          <h2 style={{ maxWidth: '24ch', marginBottom: 40 }}>D365 admins, sales heads, and Microsoft Partners — already shipping with Dynawins.</h2>
          <div className="testimonials-grid">
            <Testimonial
              quote="We rolled Smart Panel AI to 47 sales reps in one afternoon. Two weeks in, our average response time on quotes dropped from 3 days to 18 hours. Zero training needed — they just asked the panel."
              name="Priya Menon"
              role="Head of Sales Ops · Mumbai-based 3PL"
            />
            <Testimonial
              quote="As a Microsoft Partner we've integrated three vendor controls into D365 deployments. Dynawins is the only one that didn't make me file a support ticket on day one. Documentation is honest about limitations."
              name="James O'Sullivan"
              role="Practice Lead · Power Platform · Dublin"
            />
            <Testimonial
              quote="Per-environment pricing was the deal-breaker. We were quoted ₹37,000/month for Microsoft Copilot for 25 users. Smart Panel AI Pro at ₹11,999/month covers the same team, plus the Kanban control as a bonus."
              name="Rajat Sharma"
              role="CIO · Manufacturing SMB · Pune"
            />
          </div>
          <div style={{ marginTop: 32, display: 'flex', alignItems: 'center', gap: 14, fontSize: 13, color: 'var(--ink-4)', flexWrap: 'wrap' }}>
            <span className="dot-live" aria-hidden="true"/>
            <span><strong style={{ color: 'var(--ink-1)' }}>340+ D365 environments</strong> running Dynawins controls today.</span>
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="section section-ink">
        <div className="container text-center">
          <h2 style={{ maxWidth: '24ch', margin: '0 auto 16px', fontSize: 'clamp(32px, 4vw, 48px)' }}>Tell us what is broken in your D365 environment.</h2>
          <p className="lead" style={{ maxWidth: '52ch', margin: '0 auto 32px' }}>One call, no sales theatre. We will tell you whether we can help — and if not, who can.</p>
          <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
            <a className="btn btn-primary btn-lg" href="#" onClick={(e) => { e.preventDefault(); go('contact'); }}>Book a call <Icon name="arrow-right" size={16}/></a>
            <a className="btn btn-ghost btn-lg" href="#" onClick={(e) => { e.preventDefault(); go('pricing'); }} style={{ color: '#FFF', borderColor: '#525252' }}>See product pricing</a>
          </div>
        </div>
      </section>
    </div>
  );
};

const ServiceCard = ({ brand, iconName, title, body }) => (
  <div className="card">
    <div style={{ marginBottom: 16, display: 'inline-flex' }}>
      {brand
        ? <BrandIcon name={brand} size={40}/>
        : <span style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--accent-tint)', color: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={iconName} size={20}/></span>}
    </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>
);

const PRODUCT_ROUTES = { 'Smart Panel AI': 'product', 'Kanban Board': 'kanban', 'Gantt Chart': 'gantt', 'Video Playlist': 'video' };
const ProductCard = ({ accent, iconName, name, desc, status, version, badge, go }) => (
  <a className="card" href="#" onClick={(e) => { e.preventDefault(); go(PRODUCT_ROUTES[name] || 'product'); }} style={{ display: 'flex', flexDirection: 'column', gap: 16, color: 'inherit' }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{ width: 44, height: 44, borderRadius: 11, background: accent, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#FFF' }}>
        <Icon name={iconName} size={22}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ fontWeight: 700, fontSize: 17 }}>{name}</div>
          {badge && <span style={{ fontSize: 10, fontWeight: 700, background: accent + '20', color: accent, padding: '2px 7px', borderRadius: 999, letterSpacing: '0.04em' }}>{badge}</span>}
        </div>
        <div style={{ fontSize: 12, color: 'var(--ink-4)', display: 'flex', gap: 8, alignItems: 'center', marginTop: 2 }}>
          <span className="chip-mono" style={{ padding: '1px 6px' }}>{version}</span>
          <span style={{ color: status === 'Beta' ? '#A16207' : '#15803D', fontWeight: 600 }}>● {status}</span>
        </div>
      </div>
    </div>
    <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink-3)', margin: 0 }}>{desc}</p>
    <div style={{ marginTop: 'auto', fontSize: 13, fontWeight: 600, color: 'var(--accent)', display: 'flex', alignItems: 'center', gap: 6 }}>
      Learn more <Icon name="arrow-right" size={14}/>
    </div>
  </a>
);

const FeatureBlock = ({ iconName, title, body }) => (
  <div>
    <div style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--accent-tint)', color: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>
      <Icon name={iconName} size={20}/>
    </div>
    <h3 style={{ fontSize: 18, marginBottom: 8 }}>{title}</h3>
    <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink-3)', margin: 0 }}>{body}</p>
  </div>
);

// Per-name stable color (consistent avatar tint across reloads)
const TESTIMONIAL_COLORS = [
  { bg: '4F46E5', label: 'indigo' },
  { bg: '0F6CBD', label: 'blue'   },
  { bg: '15803D', label: 'green'  },
  { bg: 'A16207', label: 'amber'  },
  { bg: '742774', label: 'purple' },
];
const TESTIMONIAL_GRADIENTS = [
  'linear-gradient(135deg, #4F46E5, #EC4899)',
  'linear-gradient(135deg, #0F6CBD, #26C6DA)',
  'linear-gradient(135deg, #15803D, #84CC16)',
  'linear-gradient(135deg, #A16207, #F59E0B)',
  'linear-gradient(135deg, #742774, #A33EA1)',
];
const pickIdx = (name) =>
  (name || '').split('').reduce((a, c) => a + c.charCodeAt(0), 0)
  % TESTIMONIAL_COLORS.length;

const Testimonial = ({ quote, name, role }) => {
  const idx = pickIdx(name);
  const initials = (name || '')
    .split(' ')
    .map((s) => s[0])
    .filter(Boolean)
    .slice(0, 2)
    .join('')
    .toUpperCase();
  // ui-avatars.com is a free, hotlink-friendly avatar service. Returns a PNG of
  // the initials on a colored background. If the request is blocked (offline,
  // firewall, ad-blocker), our onError swap inserts a CSS-only gradient circle
  // so the avatar always renders something — and the name never appears twice.
  const avatarUrl = 'https://ui-avatars.com/api/?'
    + 'name=' + encodeURIComponent(name)
    + '&size=128'
    + '&background=' + TESTIMONIAL_COLORS[idx].bg
    + '&color=fff&bold=true&format=png';
  const fallbackBg = TESTIMONIAL_GRADIENTS[idx];

  return (
    <div className="testimonial">
      <div className="testimonial-stars" aria-label="5 stars">★★★★★</div>
      <div className="testimonial-quote">&ldquo;{quote}&rdquo;</div>
      <div className="testimonial-author">
        <img
          src={avatarUrl}
          alt=""           /* alt is empty so no name leak if image fails */
          aria-hidden="true"
          loading="lazy"
          className="testimonial-avatar"
          onError={(e) => {
            // Replace the broken <img> with a styled <div> showing initials.
            const div = document.createElement('div');
            div.className = 'testimonial-avatar';
            div.setAttribute('aria-hidden', 'true');
            div.style.cssText =
              'background:' + fallbackBg + ';color:#FFF;display:flex;'
              + 'align-items:center;justify-content:center;font-weight:700;'
              + 'font-size:15px;font-family:var(--font-display);'
              + 'letter-spacing:0.02em;';
            div.textContent = initials;
            e.currentTarget.replaceWith(div);
          }}
        />
        <div>
          <div className="testimonial-name">{name}</div>
          <div className="testimonial-role">{role}</div>
        </div>
      </div>
    </div>
  );
};

window.HomePage = HomePage;
