// ─────────────────────────────────────────────────────────────────────────
// Single Product — canvas preview.
//
// Mirrors the PHP element's structure and CSS: gallery column + summary,
// gallery position/thumb rail, and every section toggle. Product DATA is
// sampled locally (the editor has no WC_Product), matching the PHP
// placeholder path.
//
// The hook-driven sections (tabs / related / upsells) render as labelled
// stand-ins, because their real markup comes from WooCommerce at render time
// and can include plugin-injected tabs the editor cannot know about.
// ─────────────────────────────────────────────────────────────────────────
import React from 'react';
import type { CBNode, Breakpoint } from '../types';

function str(v: unknown, fallback = ''): string { return v == null || v === '' ? fallback : String(v); }
function num(v: unknown, fallback: number): number {
  const n = parseFloat(String(v));
  return Number.isFinite(n) ? n : fallback;
}
function px(v: unknown, fallback: string): string {
  const s = str(v);
  if (!s) return fallback;
  return /^-?[\d.]+$/.test(s) ? `${s}px` : s;
}

function Thumb({ hue }: { hue: string }) {
  return (
    <svg viewBox="0 0 600 600" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="600" height="600" fill={hue} />
      <path d="M220 380h160l-32-112h-96z" fill="#c3ccd8" />
      <circle cx="300" cy="240" r="52" fill="#c3ccd8" />
    </svg>
  );
}

const HUES = ['#eef2f7', '#f3eef7', '#eef7f2', '#f7f3ee'];

export function SingleProductPreview({
  node, inlineStyles, breakpoint,
}: { node: CBNode; inlineStyles: React.CSSProperties; breakpoint?: Breakpoint }) {
  const c = (node.content  ?? {}) as Record<string, unknown>;
  const s = (node.settings ?? {}) as Record<string, unknown>;

  const on = (k: string, d: boolean): boolean => (k in c ? !!c[k] : d);
  const show = {
    gallery: on('showGallery', true),
    title:   on('showTitle', true),
    rating:  on('showRating', true),
    price:   on('showPrice', true),
    excerpt: on('showExcerpt', true),
    cart:    on('showAddToCart', true),
    meta:    on('showMeta', true),
    share:   on('showShare', false),
    tabs:    on('showTabs', true),
    related: on('showRelated', true),
    upsells: on('showUpsells', false),
  };

  const galPos   = str(c.galleryPosition, 'left');
  const thumbPos = str(c.thumbPosition, 'horizontal');
  const titleTag = str(c.titleTag, 'h1') as 'h1' | 'h2' | 'h3' | 'div';
  const showThumbs = on('showThumbs', true);

  const galW = Math.max(20, Math.min(80, num(s.sp_gallery_width, 50)));
  const gap  = px(s.sp_col_gap, '40px');
  // Phones always stack, matching the element's mobile media query.
  const stacked = galPos === 'top' || breakpoint === 'mobile';
  const reversed = galPos === 'right';

  const imgRadius = px(s.sp_img_radius, '8px');
  const thumbSize = px(s.sp_thumb_size, '72px');
  const thumbGap  = px(s.sp_thumb_gap, '10px');

  const currency = '$';

  // ── Gallery ──────────────────────────────────────────────────────────────
  const gallery = show.gallery ? (
    <div style={{
      display: thumbPos === 'vertical' && !stacked ? 'flex' : 'block',
      flexDirection: thumbPos === 'vertical' ? 'row-reverse' : undefined,
      gap: thumbPos === 'vertical' ? thumbGap : undefined,
      alignItems: 'flex-start',
    }}>
      <div style={{ flex: '1 1 auto', minWidth: 0, borderRadius: imgRadius, overflow: 'hidden' }}>
        <Thumb hue={HUES[0]} />
      </div>
      {showThumbs && (
        <div style={{
          display: 'flex',
          flexDirection: thumbPos === 'vertical' && !stacked ? 'column' : 'row',
          flexWrap: 'wrap',
          gap: thumbGap,
          marginTop: thumbPos === 'vertical' && !stacked ? 0 : thumbGap,
          flex: thumbPos === 'vertical' && !stacked ? `0 0 ${thumbSize}` : undefined,
        }}>
          {[0, 1, 2].map((i) => (
            <span key={i} style={{
              width: thumbSize, height: thumbSize, overflow: 'hidden', lineHeight: 0,
              borderRadius: px(s.sp_thumb_radius, '6px'),
              border: `2px solid ${i === 0 ? str(s.sp_thumb_active_color, '#111827') : 'transparent'}`,
              boxSizing: 'border-box',
            }}>
              <Thumb hue={HUES[i % HUES.length]} />
            </span>
          ))}
        </div>
      )}
    </div>
  ) : null;

  // ── Summary ──────────────────────────────────────────────────────────────
  const TitleTag = titleTag;
  const summary = (
    <div>
      {show.title && (
        <TitleTag style={{
          margin: str(s.sp_title_margin, '0 0 10px'),
          fontSize: num(s.sp_title_size, 30),
          fontWeight: num(s.sp_title_weight, 700),
          lineHeight: num(s.sp_title_lh, 1.25),
          letterSpacing: str(s.sp_title_ls) ? px(s.sp_title_ls, '') : undefined,
          textTransform: (str(s.sp_title_transform, 'none') !== 'none'
            ? str(s.sp_title_transform) : undefined) as React.CSSProperties['textTransform'],
          fontFamily: str(s.sp_title_font) || undefined,
          color: str(s.sp_title_color) || undefined,
          textAlign: (str(s.sp_title_align, 'inherit') !== 'inherit'
            ? str(s.sp_title_align) : undefined) as React.CSSProperties['textAlign'],
        }}>Sample Product</TitleTag>
      )}

      {show.rating && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: num(s.sp_rating_spacing, 10) }}>
          <span style={{ position: 'relative', display: 'inline-block', width: '5.2em', height: '1em', fontSize: num(s.sp_star_size, 16), lineHeight: 1 }}>
            <span style={{ color: str(s.sp_star_empty_color, '#d1d5db'), letterSpacing: '.05em' }}>★★★★★</span>
            <span style={{ position: 'absolute', inset: 0, overflow: 'hidden', whiteSpace: 'nowrap', width: '90%' }}>
              <span style={{ color: str(s.sp_star_color, '#f59e0b'), letterSpacing: '.05em' }}>★★★★★</span>
            </span>
          </span>
          {on('showReviewCount', true) && (
            <span style={{ fontSize: num(s.sp_review_size, 13), color: str(s.sp_review_color) || undefined }}>
              12 reviews
            </span>
          )}
        </div>
      )}

      {show.price && (
        <div style={{
          display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 10,
          marginBottom: num(s.sp_price_spacing, 14),
          fontSize: num(s.sp_price_size, 24),
          fontWeight: num(s.sp_price_weight, 700),
          color: str(s.sp_price_color) || undefined,
        }}>
          {on('showRegularPrice', true) && (
            <del style={{ opacity: 0.5, fontWeight: 400, fontSize: '.75em' }}>{currency}49.00</del>
          )}
          {on('showSalePrice', true) && (
            <ins style={{ textDecoration: 'none', color: str(s.sp_sale_price_color) || undefined }}>
              {currency}39.00
            </ins>
          )}
          {on('showSaleBadge', true) && (
            <span style={{
              display: 'inline-block', fontSize: num(s.sp_badge_size, 12), fontWeight: 600, lineHeight: 1.4,
              padding: str(s.sp_badge_pad, '3px 9px'),
              borderRadius: px(s.sp_badge_radius, '4px'),
              background: str(s.sp_badge_bg, '#dc2626'),
              color: str(s.sp_badge_color, '#ffffff'),
            }}>-20%</span>
          )}
        </div>
      )}

      {show.excerpt && (
        <div style={{
          fontSize: num(s.sp_desc_size, 15),
          lineHeight: num(s.sp_desc_lh, 1.7),
          marginBottom: num(s.sp_desc_spacing, 18),
          color: str(s.sp_desc_color) || undefined,
          textAlign: (str(s.sp_desc_align, 'inherit') !== 'inherit'
            ? str(s.sp_desc_align) : undefined) as React.CSSProperties['textAlign'],
        }}>
          A short sample description for this product, shown in the editor preview.
        </div>
      )}

      {show.cart && (
        <div style={{ display: 'flex', alignItems: 'stretch', flexWrap: 'wrap', gap: 12, marginBottom: num(s.sp_cart_spacing, 20) }}>
          {on('showQuantity', true) && (
            <span style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              width: px(s.sp_qty_width, '110px'), height: px(s.sp_qty_height, '46px'),
              boxSizing: 'border-box',
              background: str(s.sp_qty_bg) || undefined,
              border: `1px solid ${str(s.sp_qty_bd_color, '#e5e7eb')}`,
              borderRadius: px(s.sp_qty_radius, '8px'),
              fontSize: num(s.sp_qty_size, 15),
              color: str(s.sp_qty_color) || undefined,
              gap: 10,
            }}>
              {str(c.quantityType, 'input') === 'plusminus' && <span style={{ color: str(s.sp_qty_btn_color) || undefined }}>−</span>}
              <span>1</span>
              {str(c.quantityType, 'input') === 'plusminus' && <span style={{ color: str(s.sp_qty_btn_color) || undefined }}>+</span>}
            </span>
          )}
          <span style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            padding: str(s.sp_btn_pad, '12px 28px'),
            fontSize: num(s.sp_btn_size, 15),
            fontWeight: num(s.sp_btn_weight, 600),
            color: str(s.sp_btn_color, '#ffffff'),
            background: str(s.sp_btn_bg, '#111827'),
            borderRadius: px(s.sp_btn_radius, '8px'),
            boxSizing: 'border-box',
            ...(str(s.sp_btn_bd_type, 'none') !== 'none'
              ? {
                  borderStyle: str(s.sp_btn_bd_type),
                  borderWidth: px(s.sp_btn_bd_width, '1px'),
                  borderColor: str(s.sp_btn_bd_color, 'currentColor'),
                }
              : {}),
          }}>
            {str(s.sp_btn_icon, 'none') !== 'none' && str(s.sp_btn_icon_pos, 'before') === 'before' && (
              <span>{({ cart: '🛒', bag: '🛍', plus: '＋', arrow: '→' } as Record<string, string>)[str(s.sp_btn_icon)]}</span>
            )}
            <span>{str(c.buttonText, 'Add to cart')}</span>
            {str(s.sp_btn_icon, 'none') !== 'none' && str(s.sp_btn_icon_pos, 'before') === 'after' && (
              <span>{({ cart: '🛒', bag: '🛍', plus: '＋', arrow: '→' } as Record<string, string>)[str(s.sp_btn_icon)]}</span>
            )}
          </span>
        </div>
      )}

      {show.meta && (
        <div style={{
          display: 'flex', flexDirection: 'column', gap: num(s.sp_meta_spacing, 6),
          fontSize: num(s.sp_meta_size, 13),
          color: str(s.sp_meta_color) || undefined,
        }}>
          {on('metaSku', true) && (
            <span>
              {on('metaShowLabels', true) && <strong style={{ color: str(s.sp_meta_label_color) || undefined }}>SKU: </strong>}
              DEMO-001
            </span>
          )}
          {on('metaCategories', true) && (
            <span>
              {on('metaShowLabels', true) && <strong style={{ color: str(s.sp_meta_label_color) || undefined }}>Category: </strong>}
              Sample
            </span>
          )}
          {on('metaTags', true) && (
            <span>
              {on('metaShowLabels', true) && <strong style={{ color: str(s.sp_meta_label_color) || undefined }}>Tags: </strong>}
              demo{str(c.metaSeparator, ', ')}preview
            </span>
          )}
        </div>
      )}

      {show.share && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 14 }}>
          {str(c.shareNetworks, 'facebook,twitter,linkedin,pinterest,whatsapp')
            .split(',').map((n) => n.trim()).filter(Boolean).map((n) => (
              <span key={n} style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                width: '2.4em', height: '2.4em', fontSize: num(s.sp_share_size, 15), lineHeight: 1,
                borderRadius: str(s.sp_share_style, 'circle') === 'circle' ? '50%'
                  : str(s.sp_share_style) === 'rounded' ? '8px' : '0',
                background: str(s.sp_share_bg, '#f3f4f6'),
                color: str(s.sp_share_color, '#111827'),
              }}>
                {({ facebook: 'f', twitter: '𝕏', linkedin: 'in', pinterest: 'P', whatsapp: '⌾' } as Record<string, string>)[n] ?? '•'}
              </span>
            ))}
        </div>
      )}
    </div>
  );

  // ── Hook-driven section stand-ins ────────────────────────────────────────
  const note: React.CSSProperties = {
    marginTop: num(s.sp_tabs_spacing, 48),
    padding: '14px 16px',
    border: '1px dashed #cbd5e1',
    borderRadius: 8,
    color: '#64748b',
    fontSize: 13,
  };

  return (
    <div style={inlineStyles}>
      <div style={{
        ...(stacked
          ? { display: 'block' }
          : {
              display: 'grid',
              gap,
              gridTemplateColumns: reversed ? `minmax(0,1fr) ${galW}%` : `${galW}% minmax(0,1fr)`,
              alignItems: 'flex-start',
            }),
        background: str(s.sp_bg) || undefined,
        padding: str(s.sp_pad) || undefined,
        margin: str(s.sp_margin) || undefined,
        borderRadius: str(s.sp_radius) ? px(s.sp_radius, '') : undefined,
        boxShadow: str(s.sp_shadow) || undefined,
        ...(str(s.sp_bd_type, 'none') !== 'none'
          ? {
              borderStyle: str(s.sp_bd_type),
              borderWidth: px(s.sp_bd_width, '1px'),
              borderColor: str(s.sp_bd_color, '#e5e7eb'),
            }
          : {}),
      }}>
        {gallery && (
          <div style={{ order: reversed && !stacked ? 2 : 1, marginBottom: stacked ? gap : undefined }}>
            {gallery}
          </div>
        )}
        <div style={{ order: reversed && !stacked ? 1 : 2 }}>{summary}</div>
      </div>

      {show.tabs && (
        <div style={note}>
          <strong>Product Tabs</strong>
          <div style={{ fontSize: 11, marginTop: 2 }}>
            Description · Additional information · Reviews — rendered by WooCommerce on the live site.
          </div>
        </div>
      )}
      {show.upsells && (
        <div style={note}>
          <strong>Upsells</strong>
          <div style={{ fontSize: 11, marginTop: 2 }}>
            {num(c.upsellsCount, 4)} products · {num(c.upsellsColumns, 4)} columns — rendered by WooCommerce.
          </div>
        </div>
      )}
      {show.related && (
        <div style={note}>
          <strong>Related Products</strong>
          <div style={{ fontSize: 11, marginTop: 2 }}>
            {num(c.relatedCount, 4)} products · {num(c.relatedColumns, 4)} columns — rendered by WooCommerce.
          </div>
        </div>
      )}
    </div>
  );
}
