/**
 * DashboardPage.tsx
 *
 * React component replacing dashboard-page.php.
 * Data is injected by PHP via wp_localize_script into window.pdfibDashboardData.
 */

import React, { useState } from 'react';

// ─── Types ────────────────────────────────────────────────────────────────────

interface DashboardStats {
  templates: number;
  documents: number;
  today: number;
}

export interface DashboardData {
  stats: DashboardStats;
  pluginVersion: string;
  isPremium: boolean;
  date: string;
  urls: {
    reactEditor: string;
    templates: string;
    settings: string;
    dashboard: string;
    purchase: string;
  };
  i18n: {
    subtitle: string;
    version: string;
    lastUpdate: string;
    statTemplates: string;
    statDocuments: string;
    statToday: string;
    createPdf: string;
    createPdfDesc: string;
    manageTemplates: string;
    manageTemplatesDesc: string;
    viewTemplates: string;
    settingsConfig: string;
    settingsDesc: string;
    openSettings: string;
    premiumFeature: string;
    openEditor: string;
    premiumMsg: string;
    guideTitle: string;
    steps: Array<{ title: string; desc: string; hint: string; url: string }>;
  };
}

declare global {
  interface Window {
    pdfibDashboardData?: DashboardData;
    showUpgradeModal?: (reason: string) => void;
  }
}

// ─── Sub-components ───────────────────────────────────────────────────────────

const StatCard: React.FC<{ value: number; label: string }> = ({ value, label }) => (
  <div className="pdfb-stat-card">
    <div className="pdfb-stat-content">
      <div className="pdfb-stat-number">{value.toLocaleString()}</div>
      <div className="pdfb-stat-label">{label}</div>
    </div>
  </div>
);

interface ActionCardProps {
  isPremium: boolean;
  locked: boolean;
  title: string;
  desc: string;
  buttonLabel: string;
  href?: string;
  premiumMsg?: string;
  primary?: boolean;
  onPremiumClick?: () => void;
}

const ActionCard: React.FC<ActionCardProps> = ({
  locked,
  title,
  desc,
  buttonLabel,
  href,
  premiumMsg,
  primary,
  onPremiumClick,
}) => {
  const cardClass = [
    'pdfb-action-card',
    primary ? 'pdfb-primary' : '',
    locked ? 'pdfb-premium-locked' : '',
  ]
    .filter(Boolean)
    .join(' ');

  return (
    <div className={cardClass}>
      <h3>
        {title}
        {locked && <span className="pdfb-premium-badge">PRO</span>}
      </h3>
      <p>{desc}</p>
      {locked ? (
        <button
          type="button"
          className={`button ${primary ? 'button-primary' : 'button-secondary'} pdfb-premium-button`}
          data-message={premiumMsg}
          onClick={onPremiumClick}
        >
          {buttonLabel}
        </button>
      ) : (
        <a href={href} className={`button ${primary ? 'button-primary' : 'button-secondary'}`}>
          {buttonLabel}
        </a>
      )}
    </div>
  );
};

interface GuideStepProps {
  number: number;
  title: string;
  desc: string;
  hint: string;
  url: string;
}

const GuideStep: React.FC<GuideStepProps> = ({ number, title, desc, hint, url }) => (
  <a href={url} className="pdfb-step pdfb-step-link">
    <span className="pdfb-step-number">{number}</span>
    <div className="pdfb-step-content">
      <h4>{title}</h4>
      <p>{desc}</p>
      <small>{hint}</small>
    </div>
  </a>
);

// ─── PRO Promo Section ───────────────────────────────────────────────────────

interface PromoCapabilityCardProps {
  icon: string;
  title: string;
  desc: string;
  items: string[];
  tone: 'blue' | 'amber' | 'violet';
}

interface PromoMetric {
  value: string;
  label: string;
}

interface PromoSection {
  title: string;
  rows: CompareRow[];
}

interface SectionHeadingProps {
  eyebrow: string;
  title: string;
  desc: string;
  align?: 'left' | 'center';
}

const SectionHeading: React.FC<SectionHeadingProps> = ({ eyebrow, title, desc, align = 'left' }) => (
  <div className={`pdfb-section-heading pdfb-section-heading--${align}`}>
    <span className="pdfb-section-heading__eyebrow">{eyebrow}</span>
    <h3>{title}</h3>
    <p>{desc}</p>
  </div>
);

const PromoCapabilityCard: React.FC<PromoCapabilityCardProps> = ({ icon, title, desc, items, tone }) => (
  <article className={`pdfb-promo-capability pdfb-promo-capability--${tone}`}>
    <div className="pdfb-promo-capability__icon" aria-hidden="true">
      {icon}
    </div>
    <div className="pdfb-promo-capability__body">
      <h4>{title}</h4>
      <p>{desc}</p>
      <ul className="pdfb-promo-capability__list">
        {items.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </div>
  </article>
);

const PROMO_HERO_METRICS: PromoMetric[] = [
  { value: 'PNG / JPG', label: 'exports image' },
  { value: '300 / 600 DPI', label: 'qualité d’impression' },
  { value: '57 modèles', label: 'textes + mentions' },
];

const PROMO_CAPABILITIES: Array<PromoCapabilityCardProps> = [
  {
    icon: '🖼️',
    title: 'Export et rendu',
    desc: 'Des sorties plus propres pour les documents publiés, archivés ou partagés.',
    items: ['PNG et JPG', '300 & 600 DPI', 'Formats de page étendus'],
    tone: 'blue',
  },
  {
    icon: '🧲',
    title: 'Précision et confort',
    desc: 'Des outils pensés pour placer et ajuster les éléments plus rapidement.',
    items: ['Grille, guides et aimantation', 'Sélection multiple', 'Raccourcis clavier'],
    tone: 'violet',
  },
  {
    icon: '📚',
    title: 'Contenus et modèles',
    desc: 'Plus de modèles prêts à l’emploi pour couvrir davantage de cas métier.',
    items: ['36 modèles de texte', '21 modèles de mentions', 'Types de document étendus'],
    tone: 'amber',
  },
];

interface CompareRow {
  feature: string;
  free: string;
  pro: string;
}

const COMPARE_SECTIONS: PromoSection[] = [
  {
    title: 'Création et export',
    rows: [
      { feature: 'Éditeur visuel drag & drop', free: '✓', pro: '✓' },
      { feature: 'Génération PDF', free: 'PDF', pro: 'PDF' },
      { feature: 'Éléments standards', free: 'Texte, image, ligne, rectangle', pro: 'Texte, image, ligne, rectangle' },
      { feature: 'Formats d’export', free: 'PDF', pro: 'PDF, PNG, JPG' },
      { feature: 'Qualité d’export max', free: '150 DPI', pro: '300 & 600 DPI' },
    ],
  },
  {
    title: 'Modèles et contenus',
    rows: [
      { feature: 'Types de document', free: 'Facture, devis', pro: 'Facture, devis, bon de commande, avoir, relevé, contrat' },
      { feature: 'Modèles de texte dynamique', free: '3 modèles', pro: '36 modèles' },
      { feature: 'Modèles de mentions', free: '3 modèles', pro: '21 modèles' },
      { feature: 'Intégration WooCommerce', free: '✓', pro: '✓' },
      { feature: 'Galerie de modèles avancés', free: '—', pro: '✓' },
    ],
  },
  {
    title: 'Précision et productivité',
    rows: [
      { feature: 'Formats de page', free: 'A4 portrait', pro: 'A3, Letter, Legal + paysage' },
      { feature: 'Navigation grille, snap & guides', free: '—', pro: '✓' },
      { feature: 'Sélection multiple & mode groupe', free: '—', pro: '✓' },
      { feature: 'Raccourcis clavier', free: '—', pro: '✓' },
      { feature: 'Couleurs canvas avancées', free: '—', pro: '✓' },
      { feature: 'Thèmes prédéfinis de l’éditeur', free: '—', pro: '✓' },
    ],
  },
];

function getCompareValueKind(value: string): 'check' | 'dash' | 'text' {
  const normalized = value.trim();
  if (normalized === '✓' || normalized.startsWith('✓')) {
    return 'check';
  }
  if (normalized === '—' || normalized === '-') {
    return 'dash';
  }
  return 'text';
}

function renderCompareValue(value: string, variant: 'free' | 'pro') {
  const kind = getCompareValueKind(value);
  const classNames = [
    'pdfb-promo-compare__value',
    `pdfb-promo-compare__value--${kind}`,
    `pdfb-promo-compare__value--${variant}`,
  ].join(' ');

  return <span className={classNames}>{kind === 'check' ? '✓' : kind === 'dash' ? '—' : value}</span>;
}

const PremiumPromoSection: React.FC<{ purchaseUrl: string }> = ({ purchaseUrl }) => {
  const [compareOpen, setCompareOpen] = useState(true);
  const compareRowsTotal = COMPARE_SECTIONS.reduce((total, section) => total + section.rows.length, 0);
  const includedInFree = COMPARE_SECTIONS.reduce(
    (total, section) => total + section.rows.filter((row) => row.free !== '—').length,
    0,
  );

  return (
    <div className="pdfb-promo-section">
      <section className="pdfb-promo-hero">
        <div className="pdfb-promo-hero__copy">
          <span className="pdfb-promo-hero__eyebrow">Découvrir PRO</span>
          <h2 className="pdfb-promo-hero__title">Une page plus structurée pour présenter la version Pro</h2>
          <p className="pdfb-promo-hero__lead">
            La présentation est désormais découpée en blocs clairs: aperçu, points forts, comparatif détaillé, formules et appel à l’action.
          </p>
          <div className="pdfb-promo-hero__actions">
            <a href={purchaseUrl} target="_blank" rel="noopener noreferrer" className="button button-primary">
              Voir les formules PRO
            </a>
            <button
              type="button"
              className="button button-secondary"
              onClick={() => setCompareOpen((current) => !current)}
            >
              {compareOpen ? 'Masquer le comparatif' : 'Voir le comparatif'}
            </button>
          </div>
          <div className="pdfb-promo-hero__chips">
            <span>PNG / JPG</span>
            <span>300 & 600 DPI</span>
            <span>57 modèles</span>
          </div>
        </div>
        <div className="pdfb-promo-hero__panel" aria-hidden="true">
          <div className="pdfb-promo-hero__panel-head">
            <div>
              <div className="pdfb-promo-hero__panel-label">Vue synthétique</div>
              <h3>Ce que la licence Pro débloque</h3>
            </div>
            <div className="pdfb-promo-hero__panel-pill">PRO</div>
          </div>
          <div className="pdfb-promo-hero__metrics">
            {PROMO_HERO_METRICS.map((metric) => (
              <div key={metric.label} className="pdfb-promo-hero__metric">
                <strong>{metric.value}</strong>
                <span>{metric.label}</span>
              </div>
            ))}
          </div>
          <div className="pdfb-promo-doc-mockup">
            <div className="pdfb-promo-doc-header" />
            <div className="pdfb-promo-doc-line pdfb-promo-doc-line--wide" />
            <div className="pdfb-promo-doc-line" />
            <div className="pdfb-promo-doc-line pdfb-promo-doc-line--short" />
            <div className="pdfb-promo-doc-divider" />
            <div className="pdfb-promo-doc-grid">
              <div className="pdfb-promo-doc-cell" />
              <div className="pdfb-promo-doc-cell" />
              <div className="pdfb-promo-doc-cell pdfb-promo-doc-cell--accent" />
              <div className="pdfb-promo-doc-cell" />
              <div className="pdfb-promo-doc-cell pdfb-promo-doc-cell--accent" />
              <div className="pdfb-promo-doc-cell" />
            </div>
            <div className="pdfb-promo-doc-badge">⭐ PRO</div>
          </div>
          <p className="pdfb-promo-hero__panel-note">Exports avancés, modèles plus nombreux et blocs métier étendus.</p>
        </div>
      </section>

      <section className="pdfb-promo-capabilities">
        <SectionHeading
          eyebrow="Fonctions Pro"
          title="Trois blocs pour lire les bénéfices plus vite"
          desc="Chaque carte résume un pilier de la version Pro afin de rendre la page plus lisible et plus pédagogique."
        />
        <div className="pdfb-promo-capabilities__grid">
          {PROMO_CAPABILITIES.map((capability) => (
            <PromoCapabilityCard key={capability.title} {...capability} />
          ))}
        </div>
      </section>

      <details
        className="pdfb-promo-compare"
        open={compareOpen}
        onToggle={(event) => setCompareOpen((event.currentTarget as HTMLDetailsElement).open)}
      >
        <summary aria-label="Basculer le tableau comparatif">
          <span className="pdfb-promo-compare__toggle-label--open">Réduire le comparatif</span>
          <span className="pdfb-promo-compare__toggle-label--closed">Voir le comparatif</span>
          <span className="pdfb-promo-compare__toggle-icon--open">▴</span>
          <span className="pdfb-promo-compare__toggle-icon--closed">▾</span>
        </summary>
        <div className="pdfb-promo-compare__header">
          <SectionHeading
            eyebrow="Comparatif détaillé"
            title="Gratuit vs PRO"
            desc="Les lignes du tableau sont regroupées par thème pour rendre les écarts plus faciles à repérer."
          />
          <div className="pdfb-promo-compare__summary">
            <strong>{includedInFree}</strong>
            <span>fonctionnalités déjà présentes dans le gratuit sur {compareRowsTotal}</span>
          </div>
        </div>
        <div className="pdfb-promo-compare__table-wrap">
          <table className="pdfb-promo-compare__table">
            <colgroup>
              <col className="pdfb-promo-compare__col--feature" />
              <col className="pdfb-promo-compare__col--free" />
              <col className="pdfb-promo-compare__col--pro" />
            </colgroup>
            <thead>
              <tr>
                <th scope="col">Fonctionnalité</th>
                <th scope="col">Gratuit</th>
                <th scope="col">PRO</th>
              </tr>
            </thead>
            <tbody>
              {COMPARE_SECTIONS.map((section) => (
                <React.Fragment key={section.title}>
                  <tr className="pdfb-promo-compare__group-row">
                    <th colSpan={3}>{section.title}</th>
                  </tr>
                  {section.rows.map((row) => (
                    <tr key={row.feature}>
                      <th scope="row">{row.feature}</th>
                      <td>{renderCompareValue(row.free, 'free')}</td>
                      <td>{renderCompareValue(row.pro, 'pro')}</td>
                    </tr>
                  ))}
                </React.Fragment>
              ))}
            </tbody>
          </table>
        </div>
      </details>

      <div className="pdfb-promo-pricing-wrapper">
        <SectionHeading
          eyebrow="Tarifs"
          title="Choisissez la formule adaptée"
          desc="Trois options lisibles pour tester, déployer ou garder la licence sans renouvellement."
          align="center"
        />
        <div className="pdfb-promo-pricing">
          <a href={purchaseUrl} target="_blank" rel="noopener noreferrer" className="pdfb-promo-plan">
            <div className="pdfb-promo-plan-period">Mensuel</div>
            <div className="pdfb-promo-plan-price">3,99€</div>
            <div className="pdfb-promo-plan-cycle">/mois</div>
            <div className="pdfb-promo-plan-note">Annulable à tout moment</div>
          </a>
          <a href={purchaseUrl} target="_blank" rel="noopener noreferrer" className="pdfb-promo-plan pdfb-promo-plan--popular">
            <div className="pdfb-promo-plan-ribbon">Option annuelle</div>
            <div className="pdfb-promo-plan-period">Annuel</div>
            <div className="pdfb-promo-plan-price">39,99€</div>
            <div className="pdfb-promo-plan-cycle">/an</div>
            <div className="pdfb-promo-plan-note">Économisez 3 mois !</div>
          </a>
          <a href={purchaseUrl} target="_blank" rel="noopener noreferrer" className="pdfb-promo-plan pdfb-promo-plan--lifetime">
            <div className="pdfb-promo-plan-ribbon">Licence à vie</div>
            <div className="pdfb-promo-plan-period">À vie</div>
            <div className="pdfb-promo-plan-price">69,99€</div>
            <div className="pdfb-promo-plan-cycle">paiement unique</div>
            <div className="pdfb-promo-plan-note">Zéro renouvellement</div>
          </a>
        </div>
      </div>

      {/* CTA final */}
      <div className="pdfb-promo-cta">
        <blockquote className="pdfb-promo-cta-quote">
          &ldquo;Des options supplémentaires pour vos documents WooCommerce.&rdquo;
        </blockquote>
        <a href={purchaseUrl} target="_blank" rel="noopener noreferrer" className="pdfb-promo-cta-button">
          Voir les formules PRO
        </a>
        <p className="pdfb-promo-cta-trust">
          ✓ Achat séparé &nbsp;·&nbsp; ✓ Activation par clé &nbsp;·&nbsp; ✓ Support du vendeur
        </p>
      </div>

    </div>
  );
};

// ─── Main component ───────────────────────────────────────────────────────────

const DashboardPage: React.FC = () => {
  const data = window.pdfibDashboardData;

  if (!data) {
    return <div style={{background:'red',color:'white',padding:'20px',fontSize:'18px'}}>❌ ERREUR: window.pdfibDashboardData est undefined — le script PHP ne charge pas les données.</div>;
  }

  const { stats, pluginVersion, isPremium, date, urls, i18n } = data;

  const handlePremiumClick = () => {
    window.showUpgradeModal?.('template');
  };

  return (
    <div className="wrap">
      <div className="pdfb-pdf-builder-dashboard">

        {/* Header */}
        <div className="pdfb-dashboard-header">
          <h1>Advanced PDF Invoice Builder</h1>
          <p className="pdfb-dashboard-subtitle">{i18n.subtitle}</p>
          <div className="pdfb-dashboard-meta">
            <span className="pdfb-version-info">
              {i18n.version.replace('%s', pluginVersion)}
            </span>
            <span className="pdfb-last-update">
              {i18n.lastUpdate.replace('%s', date)}
            </span>
          </div>
        </div>

        <div className="pdfb-dashboard-layout">
          <main className="pdfb-dashboard-layout__main">
            <PremiumPromoSection purchaseUrl={urls.purchase} />

            <section className="pdfb-dashboard-actions-section">
              <SectionHeading
                eyebrow="Accès rapides"
                title="Ouvrir les écrans clés en un clic"
                desc="Les raccourcis les plus utiles restent visibles juste après la présentation Pro."
              />
              <div className="pdfb-dashboard-actions">
                <ActionCard
                  isPremium={isPremium}
                  locked={!isPremium}
                  primary
                  title={i18n.createPdf}
                  desc={i18n.createPdfDesc}
                  buttonLabel={isPremium ? i18n.openEditor : i18n.premiumFeature}
                  href={urls.reactEditor}
                  premiumMsg={i18n.premiumMsg}
                  onPremiumClick={handlePremiumClick}
                />
                <ActionCard
                  isPremium={isPremium}
                  locked={false}
                  title={i18n.manageTemplates}
                  desc={i18n.manageTemplatesDesc}
                  buttonLabel={i18n.viewTemplates}
                  href={urls.templates}
                />
                <ActionCard
                  isPremium={isPremium}
                  locked={!isPremium}
                  title={i18n.settingsConfig}
                  desc={i18n.settingsDesc}
                  buttonLabel={isPremium ? i18n.openSettings : i18n.premiumFeature}
                  href={urls.settings}
                  premiumMsg={i18n.premiumMsg}
                  onPremiumClick={handlePremiumClick}
                />
              </div>
            </section>
          </main>

          <aside className="pdfb-dashboard-layout__sidebar">
            <section className="pdfb-dashboard-sidebar-card">
              <SectionHeading
                eyebrow="Vue rapide"
                title="Repères du tableau de bord"
                desc="Ces compteurs résument l’activité de votre installation pour garder une lecture immédiate."
              />
              <div className="pdfb-dashboard-stats pdfb-dashboard-stats--sidebar">
                <StatCard value={stats.templates} label={i18n.statTemplates} />
                <StatCard value={stats.documents} label={i18n.statDocuments} />
                <StatCard value={stats.today} label={i18n.statToday} />
              </div>
            </section>

            <div className="pdfb-dashboard-guide pdfb-dashboard-guide--sidebar">
              <h3>{i18n.guideTitle}</h3>
              <div className="pdfb-guide-steps">
                {i18n.steps.map((step, idx) => (
                  <GuideStep
                    key={idx}
                    number={idx + 1}
                    title={step.title}
                    desc={step.desc}
                    hint={step.hint}
                    url={step.url}
                  />
                ))}
              </div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
};

export default DashboardPage;
