// Configurator — shared component used by The Phone + Pre-order pages
// Each phone has independent top + bottom colour. Quantity 1–5.

const { useState: useStateC, useEffect: useEffectC } = React;

// ── Built-in product photos for all 9 combos. ──
// Uses the photo-phone-* files (transparent PNGs, properly cropped).
const STATIC_COMBO_PHOTOS = {
  'combo-flamingo-flamingo':       'assets/photo-phone-flamingo.png',
  'combo-flamingo-buttercream':    'assets/photo-phone-pink-cream.png',
  'combo-flamingo-afterdark':      'assets/photo-phone-pink-black.png',
  'combo-buttercream-flamingo':    'assets/photo-phone-marshmallow.png',
  'combo-buttercream-buttercream': 'assets/photo-phone-buttercream.png',
  'combo-buttercream-afterdark':   'assets/photo-phone-cream-black.png',
  'combo-afterdark-flamingo':      'assets/photo-phone-black-pink.png',
  'combo-afterdark-buttercream':   'assets/photo-phone-black-cream.png',
  'combo-afterdark-afterdark':     'assets/photo-phone-afterdark.png',
};

function getComboPhoto(top, bot) {
  const combo = getCombo(top, bot);
  return STATIC_COMBO_PHOTOS[combo.slotId] || STATIC_COMBO_PHOTOS['combo-buttercream-buttercream'];
}

// ── Phone preview — real product photo by combo ──
function PhonePreview({ top, bot, size = 'sm' }) {
  // size sets max-width; photos are landscape so height follows.
  const photoWidth = size === 'lg' ? 560 : size === 'md' ? 320 : 160;
  const combo = getCombo(top, bot);
  const src = getComboPhoto(top, bot);

  return (
    <div
      className="phone-preview phone-preview-photo"
      style={{
        width: photoWidth,
        maxWidth: '100%',
        margin: '0 auto',
        position: 'relative',
        overflow: 'visible',
      }}
      aria-label={combo.name + ' Ciao Bella phone'}
    >
      <img
        src={src}
        alt={combo.name + ' Ciao Bella phone'}
        style={{
          width: '100%',
          height: 'auto',
          display: 'block',
          filter: 'drop-shadow(0 14px 22px rgba(46,44,41,0.18))',
        }}
      />
    </div>
  );
}

// ── Two-track shell picker ──
function ShellPicker({ value, onChange, label }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <span className="config-section-label">{label}</span>
      <div className="shell-row">
        {PHONE_SHELLS.map(s => (
          <button
            key={s.id}
            className={'shell-swatch' + (s.id === value ? ' active' : '')}
            style={{ background: s.hex }}
            onClick={() => onChange(s.id)}
            aria-label={s.name}
            title={s.name}
          />
        ))}
      </div>
      <span className="shell-name">{getShell(value).name}</span>
    </div>
  );
}

// ── Per-phone configurator card ──
function PhoneCard({ idx, top, bot, onChangeTop, onChangeBot, onApplyPreset }) {
  return (
    <div className="phone-config-card-v2">
      <div className="phone-config-preview-wrap">
        <PhonePreview top={top} bot={bot} size="md" />
      </div>
      <div className="phone-config-info">
        <div className="config-card-head">
          <span className="label">Phone {idx + 1}</span>
          <h4 className="config-combo-name">
            <span>{getCombo(top, bot).name}</span>
            <span className="config-combo-sub">
              {getShell(top).name} top · {getShell(bot).name} base
            </span>
          </h4>
        </div>

        <div className="preset-block">
          <span className="preset-label">Colour options</span>
          <div className="preset-row">
            {PHONE_PRESETS.map(p => {
              const active = p.top === top && p.bot === bot;
              return (
                <button
                  key={p.id}
                  className={'preset-chip' + (active ? ' active' : '')}
                  onClick={() => onApplyPreset(p)}>
                  <span className="preset-chip-swatch" style={{ background: getShell(p.top).hex }} />
                  {p.name}
                </button>
              );
            })}
          </div>
        </div>

        <div className="mix-divider"><span>Or mix &amp; match</span></div>

        <ShellPicker label="Top half" value={top} onChange={onChangeTop} />
        <ShellPicker label="Bottom half" value={bot} onChange={onChangeBot} />
      </div>
    </div>
  );
}

// ── Configurator main ──
function Configurator({ phones, setPhones, quantity, setQuantity, summary }) {
  const [bumpHint, setBumpHint] = useStateC(false);

  const setTop = (idx, t) => setPhones(prev => prev.map((p, i) => i === idx ? { ...p, top: t } : p));
  const setBot = (idx, b) => setPhones(prev => prev.map((p, i) => i === idx ? { ...p, bot: b } : p));
  const setBoth = (idx, preset) => setPhones(prev => prev.map((p, i) => i === idx ? { ...p, top: preset.top, bot: preset.bot } : p));

  const tryIncrement = () => {
    if (quantity >= 5) {
      setBumpHint(true);
      return;
    }
    setQuantity(q => Math.min(5, q + 1));
  };

  const qtyLabel = quantity === 1 ? 'Solo'
    : quantity === 2 ? 'BFF bundle'
    : quantity === 3 ? 'Talking trio'
    : quantity === 4 ? 'Quartet'
    : 'Little crew';

  return (
    <div className="config-grid">
      <div>
        <div className="cord-note" role="note">
          <span className="cord-note-icon" aria-hidden="true">
            <svg viewBox="0 0 32 18" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round">
              <path d="M2 9 C 4 1, 8 1, 10 9 S 14 17, 16 9 S 20 1, 22 9 S 26 17, 30 9" />
            </svg>
          </span>
          <span className="cord-note-text">
            <strong>Quick note —</strong> the curly cord always matches the <strong>top half</strong> of the phone.
          </span>
        </div>

        <div className="config-quantity-row">
          <span className="config-quantity-label">How many phones?</span>
          <div className="qty-stepper">
            <button className="qty-btn" onClick={() => { setBumpHint(false); setQuantity(q => Math.max(1, q - 1)); }} disabled={quantity <= 1}>−</button>
            <div className="qty-display">{quantity}</div>
            <button className="qty-btn" onClick={tryIncrement}>+</button>
          </div>
          <span style={{ fontFamily: 'var(--hand)', fontWeight: 500, color: 'var(--sub-2)', fontSize: 14 }}>{qtyLabel}</span>
        </div>

        {bumpHint && (
          <div className="qty-hint" role="status">
            <span className="qty-hint-dot" />
            More than 5 phones? <a href="mailto:info@ciaobellaphone.com.au">Get in touch</a> — we&apos;ll set up a custom order for your family or school.
          </div>
        )}

        <div className="phone-list">
          {phones.map((p, i) => (
            <PhoneCard
              key={i}
              idx={i}
              top={p.top}
              bot={p.bot}
              onChangeTop={(t) => setTop(i, t)}
              onChangeBot={(b) => setBot(i, b)}
              onApplyPreset={(preset) => setBoth(i, preset)}
            />
          ))}
        </div>
      </div>

      <div>
        {summary}
      </div>
    </div>
  );
}

// ── usePhoneState — shared hook for managing the phones array ──
function usePhoneState(initialQty) {
  const [quantity, setQuantity] = useStateC(initialQty);
  const [phones, setPhones] = useStateC(() =>
    Array.from({ length: initialQty }, () => ({ top: 'buttercream', bot: 'buttercream', name: '' }))
  );

  useEffectC(() => {
    setPhones(prev => {
      if (prev.length === quantity) return prev;
      if (prev.length < quantity) {
        return [...prev, ...Array.from({ length: quantity - prev.length }, () => ({ top: 'buttercream', bot: 'buttercream', name: '' }))];
      }
      return prev.slice(0, quantity);
    });
  }, [quantity]);

  return { quantity, setQuantity, phones, setPhones };
}

Object.assign(window, { PhonePreview, ShellPicker, PhoneCard, Configurator, usePhoneState, STATIC_COMBO_PHOTOS, getComboPhoto });
