// Carimbou brand components
// - CarimbouLogo: recreates the square-rounded-badge mark with dashed border + serif C
// - LoyaltyCard: full vertical web card (mobile), theme-aware
// - WalletPass: vertical wallet-style pass (flat, gradient strip, generic — not mimicking
//   any specific branded wallet)
// - CarimbouWordmark: text treatment

function CarimbouLogo({ size = 56, color = '#2D8A6B', dark = '#1F6A51', cream = '#E8F4EB' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={{ display: 'block' }}>
      {/* drop-shadow base (darker green) */}
      <rect x="4" y="6" width="92" height="92" rx="20" fill={dark}/>
      {/* front plate */}
      <rect x="4" y="4" width="92" height="92" rx="20" fill={color}/>
      {/* dashed inner border */}
      <rect x="12" y="12" width="76" height="76" rx="14" fill="none"
        stroke={cream} strokeOpacity="0.55" strokeWidth="1.5" strokeDasharray="3 3"/>
      {/* corner dots */}
      <circle cx="20" cy="20" r="1.8" fill={cream} fillOpacity="0.7"/>
      <circle cx="80" cy="20" r="1.8" fill={cream} fillOpacity="0.7"/>
      <circle cx="20" cy="80" r="1.8" fill={cream} fillOpacity="0.7"/>
      <circle cx="80" cy="80" r="1.8" fill={cream} fillOpacity="0.7"/>
      {/* serif C */}
      <text x="50" y="70" textAnchor="middle"
        fontFamily="Fraunces, Georgia, serif" fontSize="64" fontWeight="700"
        fill={cream}>C</text>
    </svg>
  );
}

function CarimbouWordmark({ color = '#1A2E28', size = 22 }) {
  return (
    <span style={{
      fontFamily: 'Fraunces, Georgia, serif',
      fontWeight: 600, fontSize: size, letterSpacing: -0.5,
      color, display: 'inline-flex', alignItems: 'center', gap: 6,
    }}>
      Carimbou
    </span>
  );
}

// ─────────────────────────────────────────────────────────────
// Business themes (demo businesses)
// ─────────────────────────────────────────────────────────────
const BUSINESSES = {
  tapioca: {
    id: 'tapioca',
    name: 'Estação Tapioca',
    tagline: 'Excelência e tradição · desde 2000',
    instagram: '@estacaotapiocarj',
    phone: '(21) 97704-6932',
    icon: 'tapioca',
    stampColor: '#B5442A',
    cardBg: '#2B1810',
    cardAccent: '#E87D3E',
    cardText: '#F5EFE4',
    reward: 'Uma tapioca grátis',
    script: 'Tapioca',
  },
  padaria: {
    id: 'padaria',
    name: 'Padaria do Bairro',
    tagline: 'Pão fresquinho todo dia',
    instagram: '@padariadobairro',
    phone: '(21) 98123-4567',
    icon: 'bread',
    stampColor: '#7A3F1E',
    cardBg: '#F5E6CE',
    cardAccent: '#C9782F',
    cardText: '#3A2816',
    reward: 'Um pão doce grátis',
    script: 'Padaria',
  },
  esmalte: {
    id: 'esmalte',
    name: 'Studio Belli Unhas',
    tagline: 'Esmaltação, spa dos pés, nail art',
    instagram: '@studiobelli',
    phone: '(21) 99811-0022',
    icon: 'nail',
    stampColor: '#C2185B',
    cardBg: '#F9E8EF',
    cardAccent: '#D8467A',
    cardText: '#3C1A2A',
    reward: 'Uma esmaltação grátis',
    script: 'Belli',
  },
  cabelo: {
    id: 'cabelo',
    name: 'Studio Raízes',
    tagline: 'Corte, barba & escova',
    instagram: '@studioraizes',
    phone: '(21) 98455-7788',
    icon: 'scissors',
    stampColor: '#1F4A5F',
    cardBg: '#103240',
    cardAccent: '#7BC5D9',
    cardText: '#E8F4F8',
    reward: 'Um corte grátis',
    script: 'Raízes',
  },
};

// ─────────────────────────────────────────────────────────────
// LoyaltyCard — portrait, mobile-first. Used as the "web" card.
// ─────────────────────────────────────────────────────────────
function LoyaltyCard({
  business, customerName, stamps = 0, total = 10,
  stampStyle = 'textured', overrideStampColor, overrideBg, overrideAccent,
  showQR = true, compact = false,
  splashAt = null, // index of the most recent stamp to "splash"
  qrOverrideUrl = null, // real scannable QR data URL — replaces FakeQR when provided
}) {
  const b = business;
  const bg = overrideBg || b.cardBg;
  const accent = overrideAccent || b.cardAccent;
  const text = b.cardText;
  const stampColor = overrideStampColor || b.stampColor;
  const grid = buildStampGrid(total);

  return (
    <div style={{
      width: compact ? 280 : 340,
      borderRadius: 24, background: bg, color: text,
      position: 'relative', overflow: 'hidden',
      fontFamily: 'Plus Jakarta Sans, system-ui, sans-serif',
      boxShadow: '0 24px 60px rgba(0,0,0,0.28), 0 6px 16px rgba(0,0,0,0.18), inset 0 1px 0 rgba(255,255,255,0.06)',
      border: '1px solid rgba(255,255,255,0.06)',
    }}>
      {/* subtle noise / paper overlay */}
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(ellipse at 30% 0%, ${accent}18 0%, transparent 55%),
                     radial-gradient(ellipse at 80% 100%, ${accent}10 0%, transparent 55%)`,
        pointerEvents: 'none',
      }} />

      {/* top: business header — the Fidelidade/Carimbou label row lives in the
          wallet detail's unified top bar now (see CardDetail in stamp-web.js),
          so the card itself starts straight at the business name/logo. */}
      <div style={{ padding: '24px 22px 12px', position: 'relative' }}>
        {b.logoUrl ? (
          // Logo-as-title: when a card logo is set it replaces the text name;
          // the tagline below stays. Caps height/width and contains so it never
          // overflows the card; left-aligned to match the text name it replaces.
          <div style={{ height: 46, display: 'flex', alignItems: 'center', justifyContent: 'flex-start' }}>
            <img src={b.logoUrl} alt={b.name}
              style={{ maxHeight: '100%', maxWidth: '85%', objectFit: 'contain', objectPosition: 'left center', display: 'block' }}/>
          </div>
        ) : (
          <div style={{
            fontFamily: 'Fraunces, Georgia, serif', fontSize: 28,
            fontWeight: 600, lineHeight: 1.05, letterSpacing: -0.8, textAlign: 'left',
          }}>
            {b.name}
          </div>
        )}
        <div style={{ fontSize: 11.5, opacity: 0.6, marginTop: 4, letterSpacing: 0.1, textAlign: 'left' }}>
          {b.tagline}
        </div>
      </div>

      {/* stamp area */}
      <div style={{
        margin: '6px 18px', padding: '18px 14px',
        borderRadius: 18,
        background: 'rgba(255,255,255,0.04)',
        border: '1px dashed rgba(255,255,255,0.12)',
        position: 'relative',
      }}>
        <div style={{
          display: 'grid', gridTemplateColumns: `repeat(${grid.cols}, 1fr)`,
          gap: 8, justifyItems: 'center',
        }}>
          {Array.from({ length: total }).map((_, i) => {
            const filled = i < stamps;
            return (
              <div key={i} style={{
                width: '100%', aspectRatio: '1',
                borderRadius: 12,
                background: filled ? 'rgba(255,255,255,0.02)' : 'rgba(0,0,0,0.15)',
                border: filled ? '1px solid rgba(255,255,255,0.06)' : '1px dashed rgba(255,255,255,0.18)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                position: 'relative',
                transition: 'all 300ms cubic-bezier(.3,1.4,.5,1)',
              }}>
                <div style={{
                  color: filled ? stampColor : text,
                  animation: splashAt === i ? 'stampIn 400ms cubic-bezier(.3,1.6,.4,1)' : undefined,
                }}>
                  <StampIcon
                    icon={b.icon}
                    filled={filled}
                    style={stampStyle}
                    color={stampColor}
                    size={36}
                    seed={i + (b.id.charCodeAt(0) || 1)}
                  />
                </div>
                {/* sequence number */}
                {!filled && (
                  <span style={{
                    position: 'absolute', top: 3, left: 5,
                    fontSize: 8, fontWeight: 700, opacity: 0.3,
                    fontFamily: 'JetBrains Mono, monospace',
                  }}>{String(i + 1).padStart(2, '0')}</span>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* middle: customer + progress */}
      <div style={{ padding: '10px 22px 0' }}>
        <div style={{ fontSize: 10, opacity: 0.5, letterSpacing: 1.2, textTransform: 'uppercase', fontWeight: 700, textAlign: 'left' }}>
          Cliente
        </div>
        <div style={{
          fontFamily: 'Fraunces, serif', fontSize: 20, fontWeight: 500,
          marginTop: 2, letterSpacing: -0.3, textAlign: 'left',
        }}>
          {customerName || '—'}
        </div>
      </div>

      {/* progress */}
      <div style={{ padding: '10px 22px 0' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 10, opacity: 0.5, letterSpacing: 1.2, textTransform: 'uppercase', fontWeight: 700 }}>
            Carimbos
          </span>
          <span style={{ fontFamily: 'Fraunces, serif', fontSize: 18, fontWeight: 600 }}>
            <span style={{ color: accent }}>{stamps}</span>
            <span style={{ opacity: 0.4 }}>/{total}</span>
          </span>
        </div>
        <div style={{ height: 4, borderRadius: 4, background: 'rgba(255,255,255,0.1)', marginTop: 6, overflow: 'hidden' }}>
          <div style={{
            height: '100%', width: `${(stamps / total) * 100}%`,
            background: accent, borderRadius: 4,
            transition: 'width 400ms ease',
          }}/>
        </div>
        <div style={{ fontSize: 10.5, opacity: 0.55, marginTop: 8, lineHeight: 1.4 }}>
          Prêmio ao completar: <span style={{ color: accent, fontWeight: 600 }}>{b.reward}</span>
        </div>
      </div>

      {/* QR — large, scannable from a phone (web cards are shared as images on WhatsApp) */}
      {showQR && (
        <div style={{ padding: '14px 22px 6px', display: 'flex', justifyContent: 'center' }}>
          <div style={{
            background: '#fff', padding: 10, borderRadius: 12,
            position: 'relative',
            boxShadow: '0 4px 14px rgba(0,0,0,0.22)',
          }}>
            {qrOverrideUrl
              ? <img src={qrOverrideUrl} width={160} height={160} style={{ display: 'block', borderRadius: 4 }}/>
              : <FakeQR size={100} fg="#111" seed={b.id + '-' + (customerName || 'x')}/>
            }
            <div style={{
              position: 'absolute', top: '50%', left: '50%',
              transform: 'translate(-50%, -50%)',
              width: 30, height: 30, borderRadius: 8,
              background: accent, color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'Fraunces, serif', fontWeight: 700, fontSize: 17,
              boxShadow: '0 0 0 3px #fff',
            }}>C</div>
          </div>
        </div>
      )}
      <div style={{ textAlign: 'center', fontSize: 9.5, opacity: 0.55, padding: '0 22px 14px' }}>
        Mostre para o atendente · {b.instagram}
      </div>
    </div>
  );
}

// Helper: pick a grid shape for a given stamp count
function buildStampGrid(total) {
  if (total <= 6) return { cols: 3, rows: Math.ceil(total / 3) };
  if (total <= 10) return { cols: 5, rows: Math.ceil(total / 5) };
  if (total <= 12) return { cols: 4, rows: Math.ceil(total / 4) };
  return { cols: 5, rows: Math.ceil(total / 5) };
}

// ─────────────────────────────────────────────────────────────
// WalletPass — generic vertical pass (NOT mimicking Apple/Google specifically)
// Header strip, logo text, primary field, secondary fields, QR
// ─────────────────────────────────────────────────────────────
function WalletPass({ business, customerName, stamps = 0, total = 10, stampStyle = 'textured' }) {
  const b = business;
  return (
    <div style={{
      width: 300, height: 440,
      borderRadius: 18,
      background: b.cardBg,
      color: b.cardText,
      fontFamily: 'Plus Jakarta Sans, system-ui, sans-serif',
      boxShadow: '0 20px 50px rgba(0,0,0,0.28), 0 2px 6px rgba(0,0,0,0.15)',
      position: 'relative', overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* top colored strip */}
      <div style={{
        height: 72, background: b.cardAccent,
        padding: '14px 18px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{ fontSize: 9, letterSpacing: 1.5, textTransform: 'uppercase', fontWeight: 700, opacity: 0.8, color: '#fff' }}>
            Carimbou · Fidelidade
          </div>
          <div style={{ fontFamily: 'Fraunces, serif', fontSize: 18, fontWeight: 600, marginTop: 2, color: '#fff' }}>
            {b.name}
          </div>
        </div>
        <CarimbouLogo size={36} color="rgba(255,255,255,0.15)" dark="rgba(0,0,0,0.15)" cream="#fff"/>
      </div>

      {/* primary field */}
      <div style={{ padding: '14px 18px 10px' }}>
        <div style={{ fontSize: 9, letterSpacing: 1.2, textTransform: 'uppercase', fontWeight: 700, opacity: 0.55 }}>Carimbos</div>
        <div style={{ fontFamily: 'Fraunces, serif', fontSize: 40, fontWeight: 600, lineHeight: 1, marginTop: 2 }}>
          <span style={{ color: b.cardAccent }}>{stamps}</span><span style={{ opacity: 0.35 }}> / {total}</span>
        </div>
      </div>

      {/* mini stamp grid */}
      <div style={{ padding: '0 18px', flex: 1 }}>
        <div style={{
          display: 'grid', gridTemplateColumns: `repeat(${buildStampGrid(total).cols}, 1fr)`,
          gap: 4,
        }}>
          {Array.from({ length: total }).map((_, i) => {
            const filled = i < stamps;
            return (
              <div key={i} style={{
                aspectRatio: '1',
                borderRadius: 8,
                border: '1px dashed rgba(255,255,255,0.18)',
                background: 'rgba(0,0,0,0.12)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <StampIcon icon={b.icon} filled={filled} style={stampStyle} color={b.stampColor} size={22} seed={i+1}/>
              </div>
            );
          })}
        </div>
      </div>

      {/* secondary fields */}
      <div style={{ padding: '10px 18px', display: 'flex', gap: 16, fontSize: 10.5 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 9, letterSpacing: 1.2, textTransform: 'uppercase', fontWeight: 700, opacity: 0.55 }}>Cliente</div>
          <div style={{ fontWeight: 600, marginTop: 2 }}>{customerName || '—'}</div>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 9, letterSpacing: 1.2, textTransform: 'uppercase', fontWeight: 700, opacity: 0.55 }}>Prêmio</div>
          <div style={{ fontWeight: 600, marginTop: 2, color: b.cardAccent }}>{b.reward}</div>
        </div>
      </div>

      {/* QR */}
      <div style={{
        padding: '10px 18px 18px', display: 'flex', justifyContent: 'center',
        background: '#fff', margin: 0,
      }}>
        <div style={{ background: '#fff', padding: 10, borderRadius: 8 }}>
          <FakeQR size={80} fg="#000" seed={b.id}/>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// FakeQR — stable per-seed ornamental QR
// ─────────────────────────────────────────────────────────────
function FakeQR({ size = 60, fg = '#000', seed = 'x' }) {
  const N = 19;
  // deterministic pseudo-random from seed
  let s = 0;
  for (let i = 0; i < seed.length; i++) s = (s * 31 + seed.charCodeAt(i)) & 0xffff;
  const rnd = () => { s = (s * 9301 + 49297) & 0xffff; return (s & 0xff) / 255; };
  const cells = [];
  for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) {
    cells.push({ x, y, on: rnd() > 0.5 });
  }
  const cell = size / N;
  const isFinder = (x, y) => {
    const inBox = (ox, oy) => x >= ox && x < ox + 7 && y >= oy && y < oy + 7;
    return inBox(0, 0) || inBox(N - 7, 0) || inBox(0, N - 7);
  };
  const isFinderInner = (x, y) => {
    const inBox = (ox, oy) => x >= ox + 2 && x < ox + 5 && y >= oy + 2 && y < oy + 5;
    return inBox(0, 0) || inBox(N - 7, 0) || inBox(0, N - 7);
  };
  return (
    <svg width={size} height={size} viewBox={`0 0 ${N} ${N}`} shapeRendering="crispEdges">
      {cells.map((c, i) => {
        if (isFinder(c.x, c.y)) return null;
        return c.on && <rect key={i} x={c.x} y={c.y} width="1" height="1" fill={fg}/>;
      })}
      {/* three finder boxes */}
      {[[0,0], [N-7,0], [0,N-7]].map(([ox, oy], i) => (
        <g key={i}>
          <rect x={ox} y={oy} width="7" height="7" fill="none" stroke={fg} strokeWidth="1"/>
          <rect x={ox+2} y={oy+2} width="3" height="3" fill={fg}/>
        </g>
      ))}
    </svg>
  );
}

Object.assign(window, {
  CarimbouLogo, CarimbouWordmark, LoyaltyCard, WalletPass, FakeQR, BUSINESSES,
  buildStampGrid, StampIcon,
});
