import type { CSSProperties, ReactNode } from 'react';
import { EMAIL_FONT_STACKS, FORM_TEXT_DEFAULTS } from '../constants';
import type { Settings } from '../types';
import { __, _n, sprintf } from "@wordpress/i18n";
export type EmailPreviewType = 'restock' | 'confirmation';
const EMAIL_LAYOUT_STYLES = {
  email_layout_classic: {
    cardBg: '#ffffff',
    cardBorder: '#e2e8f0',
    cardRadius: '10px',
    cardShadow: '0 10px 30px rgba(15,23,42,.08)',
    headingSize: '30px',
    ctaRadius: '8px',
    ctaPadding: '11px 16px'
  },
  email_layout_soft: {
    cardBg: '#f8fafc',
    cardBorder: '#e2e8f0',
    cardRadius: '14px',
    cardShadow: '0 8px 24px rgba(15,23,42,.08)',
    headingSize: '28px',
    ctaRadius: '999px',
    ctaPadding: '11px 18px'
  },
  email_layout_minimal: {
    cardBg: '#ffffff',
    cardBorder: '#f1f5f9',
    cardRadius: '6px',
    cardShadow: '0 2px 8px rgba(15,23,42,.05)',
    headingSize: '27px',
    ctaRadius: '6px',
    ctaPadding: '10px 14px'
  },
  email_layout_strong: {
    cardBg: '#ffffff',
    cardBorder: '#cbd5e1',
    cardRadius: '12px',
    cardShadow: '0 14px 34px rgba(15,23,42,.14)',
    headingSize: '32px',
    ctaRadius: '10px',
    ctaPadding: '12px 18px'
  },
  email_layout_editorial: {
    cardBg: '#ffffff',
    cardBorder: '#dbe4ef',
    cardRadius: '4px',
    cardShadow: '0 18px 42px rgba(15,23,42,.10)',
    headingSize: '34px',
    ctaRadius: '4px',
    ctaPadding: '12px 20px'
  },
  email_layout_compact: {
    cardBg: '#ffffff',
    cardBorder: '#e5e7eb',
    cardRadius: '8px',
    cardShadow: '0 3px 12px rgba(15,23,42,.06)',
    headingSize: '24px',
    ctaRadius: '6px',
    ctaPadding: '9px 13px'
  },
  email_layout_warm_note: {
    cardBg: '#fffbeb',
    cardBorder: '#fde68a',
    cardRadius: '16px',
    cardShadow: '0 10px 26px rgba(146,64,14,.10)',
    headingSize: '29px',
    ctaRadius: '12px',
    ctaPadding: '11px 18px'
  },
  email_layout_receipt: {
    cardBg: '#ffffff',
    cardBorder: '#d1d5db',
    cardRadius: '2px',
    cardShadow: '0 1px 0 rgba(15,23,42,.08)',
    headingSize: '26px',
    ctaRadius: '3px',
    ctaPadding: '10px 16px'
  },
  email_layout_product_drop: {
    cardBg: '#f0f9ff',
    cardBorder: '#bae6fd',
    cardRadius: '18px',
    cardShadow: '0 18px 38px rgba(2,132,199,.14)',
    headingSize: '33px',
    ctaRadius: '999px',
    ctaPadding: '12px 22px'
  },
  email_layout_enterprise: {
    cardBg: '#f8fafc',
    cardBorder: '#94a3b8',
    cardRadius: '6px',
    cardShadow: '0 8px 18px rgba(15,23,42,.09)',
    headingSize: '28px',
    ctaRadius: '4px',
    ctaPadding: '11px 17px'
  },
  email_layout_airmail: {
    cardBg: '#fefefe',
    cardBorder: '#bfdbfe',
    cardRadius: '12px',
    cardShadow: '0 12px 28px rgba(37,99,235,.10)',
    headingSize: '30px',
    ctaRadius: '999px',
    ctaPadding: '11px 20px'
  },
  email_layout_luxe: {
    cardBg: '#fff7ed',
    cardBorder: '#fed7aa',
    cardRadius: '20px',
    cardShadow: '0 20px 44px rgba(154,52,18,.13)',
    headingSize: '31px',
    ctaRadius: '14px',
    ctaPadding: '12px 20px'
  },
  email_layout_clean_line: {
    cardBg: '#ffffff',
    cardBorder: '#e0f2fe',
    cardRadius: '0px',
    cardShadow: '0 0 0 rgba(0,0,0,0)',
    headingSize: '29px',
    ctaRadius: '0px',
    ctaPadding: '11px 16px'
  },
  email_layout_soft_panel: {
    cardBg: '#f5f3ff',
    cardBorder: '#ddd6fe',
    cardRadius: '18px',
    cardShadow: '0 14px 34px rgba(91,33,182,.10)',
    headingSize: '30px',
    ctaRadius: '10px',
    ctaPadding: '12px 19px'
  }
};
const PREVIEW_TAG_VALUES: Record<string, string> = {
  '{product_name}': 'Premium Hoodie',
  '{product_url}': 'https://example.com/products/premium-hoodie',
  '{product_price}': '$49.00',
  '{store_name}': 'Your Store',
  '{confirm_url}': 'https://example.com/?stockbeacon_confirm=abc123'
};
function clampNumber(value: unknown, fallback: number, min: number, max: number): number {
  const next = Number(value);
  if (!Number.isFinite(next)) return fallback;
  return Math.max(min, Math.min(max, next));
}
function getReadableInputColors(background: string | undefined) {
  const hex = /^#([0-9a-f]{6})$/i.exec(String(background || ''));
  if (!hex) {
    return {
      text: '#0f172a',
      placeholder: '#64748b'
    };
  }
  const rgb = hex[1].match(/[0-9a-f]{2}/gi)?.map(part => parseInt(part, 16)) || [255, 255, 255];
  const [r, g, b] = rgb.map(channel => {
    const value = channel / 255;
    return value <= 0.03928 ? value / 12.92 : Math.pow((value + 0.055) / 1.055, 2.4);
  });
  const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
  return luminance > 0.42 ? {
    text: '#0f172a',
    placeholder: '#64748b'
  } : {
    text: '#f8fafc',
    placeholder: '#94a3b8'
  };
}
function interpolate(value: string): string {
  return Object.entries(PREVIEW_TAG_VALUES).reduce((text, [tag, replacement]) => text.split(tag).join(replacement), value);
}
function renderEmailBody(body: string): ReactNode[] {
  const blocks = body.trim().split(/\n\s*\n/).filter(Boolean);
  const paragraphs = blocks.length ? blocks : [__('The product you were waiting for is now available. Grab it before it sells out again!', 'stockbeacon-product-waitlists-for-woocommerce')];
  return paragraphs.map((block, index) => <p key={index} style={{
    margin: index === 0 ? '0' : '16px 0 0'
  }}>
			{block.split('\n').map((line, lineIndex) => <span key={lineIndex}>
					{lineIndex > 0 && <br />}
					{line}
				</span>)}
		</p>);
}
interface FormDesignPreviewProps {
  settings: Settings;
  count?: number;
}
export function FormDesignPreview({
  settings: s,
  count = 32
}: FormDesignPreviewProps) {
  const showCount = s.show_waitlist_count !== false;
  const showConsent = !!s.show_consent_checkbox;
  const accent = s.form_accent_color || '#2563eb';
  const button = s.form_button_color || accent;
  const inputColors = getReadableInputColors(s.form_input_background_color || (s.form_theme_mode === 'dark' ? '#0f172a' : '#ffffff'));
  let radius = 6;
  
  const style = {
    '--stockbeacon-accent': accent,
    '--stockbeacon-button': button,
    '--stockbeacon-button-hover': `color-mix(in srgb, ${button} 86%, #0f172a)`,
    '--stockbeacon-radius': `${radius}px`,
    '--stockbeacon-bg': s.form_background_color || '#ffffff',
    '--stockbeacon-text': s.form_text_color || (s.form_theme_mode === 'dark' ? '#f8fafc' : '#0f172a'),
    '--stockbeacon-text-muted': s.form_description_color || (s.form_theme_mode === 'dark' ? '#cbd5e1' : '#64748b'),
    '--stockbeacon-input-bg': s.form_input_background_color || (s.form_theme_mode === 'dark' ? '#0f172a' : '#ffffff'),
    '--stockbeacon-input-text': inputColors.text,
    '--stockbeacon-input-placeholder': inputColors.placeholder,
    '--stockbeacon-count-text': s.form_count_text_color || (s.form_theme_mode === 'dark' ? '#14532d' : '#334155'),
    '--stockbeacon-title-font-size': `${clampNumber(s.form_title_font_size, 17, 12, 32)}px`,
    '--stockbeacon-description-font-size': `${clampNumber(s.form_description_font_size, 14, 11, 24)}px`,
    '--stockbeacon-input-font-size': `${clampNumber(s.form_input_font_size, 16, 12, 22)}px`,
    '--stockbeacon-button-font-size': `${clampNumber(s.form_button_font_size, 14, 12, 22)}px`,
    '--stockbeacon-count-font-size': `${clampNumber(s.form_count_font_size, 13, 10, 18)}px`,
    '--stockbeacon-success-font-size': `${clampNumber(s.form_success_font_size, 15, 11, 24)}px`,
    ...(s.form_box_shadow_enabled === false ? {
      '--stockbeacon-shadow': 'none'
    } : {})
  } as CSSProperties;
  return <div id="stockbeacon-preview" className={`stockbeacon-form-wrapper stockbeacon-template-${s.form_template || 'card'} stockbeacon-theme-${s.form_theme_mode === 'dark' ? 'dark' : 'light'}`} style={style} data-product-id="123" data-variation-id="0" data-show-count={showCount ? '1' : '0'}>
			<div className="stockbeacon-form">
				<div className="stockbeacon-head">
					<h4 className="stockbeacon-title">{s.form_title || FORM_TEXT_DEFAULTS.form_title}</h4>
					<p className="stockbeacon-description">{s.form_description || FORM_TEXT_DEFAULTS.form_description}</p>
				</div>
				<div className="stockbeacon-input-group">
					<input type="email" className="stockbeacon-email" placeholder={s.form_placeholder || FORM_TEXT_DEFAULTS.form_placeholder} autoComplete="email" enterKeyHint="send" inputMode="email" readOnly />
					<button type="button" className="stockbeacon-submit button">
						{s.form_button_text || FORM_TEXT_DEFAULTS.form_button_text}
					</button>
				</div>
				{showConsent && <label className="stockbeacon-consent">
						<input type="checkbox" className="stockbeacon-consent-checkbox" defaultChecked readOnly />
						<span>{s.consent_text || __('I agree to receive a one-time restock notification for this product.', 'stockbeacon-product-waitlists-for-woocommerce')}</span>
					</label>}
				{showCount && <p className="stockbeacon-count" role="status" data-singular={__('%d person is waiting', 'stockbeacon-product-waitlists-for-woocommerce')} data-plural={__('%d people are waiting', 'stockbeacon-product-waitlists-for-woocommerce')}>
						<span className="stockbeacon-count__dot" aria-hidden="true" />
						<span className="stockbeacon-count__text">{sprintf(_n('%d person is waiting', '%d people are waiting', count, 'stockbeacon-product-waitlists-for-woocommerce'), count)}</span>
					</p>}
				<div className="stockbeacon-message" style={{
        display: 'none'
      }} />
			</div>
			<div className="stockbeacon-success" style={{
      display: 'none'
    }}>
				<p className="stockbeacon-success-message">{s.form_success_message || FORM_TEXT_DEFAULTS.form_success_message}</p>
			</div>
		</div>;
}
interface EmailDesignPreviewProps {
  settings: Settings;
  emailType?: EmailPreviewType;
}
export function EmailDesignPreview({
  settings: s,
  emailType = 'restock'
}: EmailDesignPreviewProps) {
  let presetId: keyof typeof EMAIL_LAYOUT_STYLES = 'email_layout_classic';
  
  const layout = EMAIL_LAYOUT_STYLES[presetId] || EMAIL_LAYOUT_STYLES.email_layout_classic;
  const accent = s.email_accent_color || s.form_accent_color || '#2563eb';
  const background = s.email_background_color || '#f1f5f9';
  const cardBg = s.email_card_background_color || layout.cardBg;
  const fontKey = String(s.email_font_family || 'system');
  const fontFamily = EMAIL_FONT_STACKS[fontKey] || EMAIL_FONT_STACKS.system;
  const headingSize = clampNumber(s.email_heading_font_size, parseInt(layout.headingSize, 10) || 30, 18, 48);
  const bodySize = clampNumber(s.email_body_font_size, 16, 12, 24);
  const buttonSize = clampNumber(s.email_button_font_size, 15, 12, 22);
  const footerSize = clampNumber(s.email_footer_font_size, 12, 10, 16);
  const cardShadow = s.email_box_shadow_enabled === true ? layout.cardShadow : 'none';
  const isConfirm = emailType === 'confirmation';
  const heading = interpolate(isConfirm ? s.confirmation_email_heading || __('One more step', 'stockbeacon-product-waitlists-for-woocommerce') : s.restock_email_heading || __("Great news - it's back!", 'stockbeacon-product-waitlists-for-woocommerce'));
  const body = interpolate(isConfirm ? s.confirmation_email_body || __('Please confirm that you want to be notified when {product_name} is back in stock.', 'stockbeacon-product-waitlists-for-woocommerce') : s.restock_email_body || __('The product you were waiting for is now available. Grab it before it sells out again!', 'stockbeacon-product-waitlists-for-woocommerce'));
  const cta = interpolate(isConfirm ? s.confirmation_email_cta_text || __('Confirm Subscription', 'stockbeacon-product-waitlists-for-woocommerce') : s.restock_email_cta_text || __('Shop Now', 'stockbeacon-product-waitlists-for-woocommerce'));
  return <div className="stockbeacon-email-preview">
			<div className="stockbeacon-email-preview__body" style={{
      background,
      color: '#1f2937',
      fontFamily
    }}>
				<table role="presentation" width="100%" cellSpacing={0} cellPadding={0} style={{
        borderCollapse: 'collapse'
      }}>
					<tbody>
						<tr>
							<td align="center">
								<table role="presentation" width="100%" cellSpacing={0} cellPadding={0} style={{
                maxWidth: 640,
                borderCollapse: 'collapse'
              }}>
									<tbody>
										<tr>
											<td style={{
                      padding: 24,
                      background: cardBg,
                      border: `1px solid ${layout.cardBorder}`,
                      borderRadius: layout.cardRadius,
                      boxShadow: cardShadow
                    }}>
												<h1 style={{
                        margin: '0 0 12px',
                        fontSize: headingSize,
                        lineHeight: 1.2,
                        fontWeight: 700,
                        color: '#111827'
                      }}>
													{heading}
												</h1>
												<div style={{
                        margin: '0 0 16px',
                        fontSize: bodySize,
                        lineHeight: 1.65,
                        color: '#374151'
                      }}>
													{renderEmailBody(body)}
												</div>
												<p style={{
                        margin: 0
                      }}>
													<a href="#" style={{
                          display: 'inline-block',
                          background: accent,
                          color: '#ffffff',
                          textDecoration: 'none',
                          padding: layout.ctaPadding,
                          borderRadius: layout.ctaRadius,
                          fontSize: buttonSize,
                          fontWeight: 700
                        }} onClick={e => e.preventDefault()}>
														{cta}
													</a>
												</p>
												{!isConfirm && <p style={{
                        margin: '14px 0 0',
                        fontSize: footerSize,
                        lineHeight: 1.45
                      }}>
														<a href="#" style={{
                          color: '#64748b',
                          textDecoration: 'underline'
                        }} onClick={e => e.preventDefault()}>{__("Unsubscribe", "stockbeacon-product-waitlists-for-woocommerce")}</a>
													</p>}
												{isConfirm && <p style={{
                        margin: '16px 0 0',
                        fontSize: footerSize,
                        lineHeight: 1.45,
                        color: '#787c82'
                      }}>{__("This is a confirmation email preview. The confirmation button uses the subscriber's secure link.", "stockbeacon-product-waitlists-for-woocommerce")}</p>}
											</td>
										</tr>
									</tbody>
								</table>
							</td>
						</tr>
					</tbody>
				</table>
			</div>
		</div>;
}
