// page-styles.jsx — the 3 public-page renderings + shared bits

// ────────────────────────────────────────────────────────────
// Palettes (named themes)
// ────────────────────────────────────────────────────────────
const PALETTES = {
  cream: { name: 'Linho', bg: '#f3eee4', surface: '#ffffff', ink: '#1f1b14', ink2: '#615b4e', accent: '#1f1b14', cta: '#1f1b14', ctaInk: '#fdfaf3', tag: '#e6dfd0' },
  noir:  { name: 'Noir',  bg: '#0e0e10', surface: '#19191d', ink: '#f4f0e8', ink2: '#a8a39a', accent: '#f4f0e8', cta: '#f4f0e8', ctaInk: '#0e0e10', tag: '#2a2a31' },
  fresh: { name: 'Fresh', bg: '#eaf3ec', surface: '#ffffff', ink: '#103024', ink2: '#446a59', accent: '#1d6b4a', cta: '#1d6b4a', ctaInk: '#ffffff', tag: '#d2e7d8' },
  sun:   { name: 'Sol',   bg: '#fff1d6', surface: '#ffffff', ink: '#2d1810', ink2: '#7b4e2a', accent: '#c84a17', cta: '#c84a17', ctaInk: '#ffffff', tag: '#ffe1ad' },
  sky:   { name: 'Céu',   bg: '#e6ecf5', surface: '#ffffff', ink: '#0f1b3a', ink2: '#4c597a', accent: '#3046b8', cta: '#3046b8', ctaInk: '#ffffff', tag: '#d5dcec' },
};

// ────────────────────────────────────────────────────────────
// Profile header (shared across all 3 styles, with slight variants)
// ────────────────────────────────────────────────────────────
function Avatar({ name, src, size = 84, palette, ring = true }) {
  const shadow = ring ? `0 0 0 4px ${palette.surface}, 0 0 0 5px ${palette.ink}1a` : 'none';
  const base = { width: size, height: size, borderRadius: '50%', boxShadow: shadow, flexShrink: 0, overflow: 'hidden' };
  if (src) {
    return (
      <div style={{ ...base, background: '#ddd' }}>
        <img src={src} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
      </div>
    );
  }
  const initials = (name || '').split(' ').filter(Boolean).slice(0, 2).map(s => s[0].toUpperCase()).join('');
  const hash = [...(name || 'A')].reduce((a, c) => a + c.charCodeAt(0), 0);
  const hue1 = hash % 360, hue2 = (hue1 + 40) % 360;
  return (
    <div style={{
      ...base,
      background: `linear-gradient(135deg, oklch(0.85 0.08 ${hue1}), oklch(0.65 0.13 ${hue2}))`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: '#fff', fontWeight: 600, fontSize: size * 0.36, letterSpacing: '-0.02em',
    }}>{initials}</div>
  );
}

function ProfileHeader({ profile, palette, dense = false }) {
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      padding: dense ? '20px 24px 16px' : '40px 24px 24px', textAlign: 'center',
    }}>
      <Avatar name={profile.name} src={profile.avatar} size={dense ? 64 : 88} palette={palette} />
      <div style={{ height: dense ? 12 : 18 }} />
      <div style={{
        fontFamily: "'Plus Jakarta Sans', sans-serif",
        fontWeight: 700, fontSize: dense ? 19 : 22, letterSpacing: '-0.02em',
        color: palette.ink,
      }}>{profile.name}</div>
      <div style={{
        fontSize: 13, color: palette.ink2, marginTop: 4, fontWeight: 500,
      }}>@{profile.handle}</div>
      {profile.bio && (
        <div style={{
          marginTop: 12, fontSize: 14, lineHeight: 1.45, color: palette.ink2,
          maxWidth: 280, textWrap: 'pretty',
        }}>{profile.bio}</div>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// STYLE 1 — CLÁSSICO (vertical button list, minimal)
// ────────────────────────────────────────────────────────────
function StyleClassic({ profile, links, palette }) {
  const I = window.Icon;
  return (
    <div style={{ minHeight: '100%', color: palette.ink }}>
      <ProfileHeader profile={profile} palette={palette} />
      <div style={{
        padding: '8px 20px 80px', display: 'flex', flexDirection: 'column', gap: 12,
      }}>
        {links.map(link => {
          const Ico = I[link.icon] || I.link;
          return (
            <a key={link.id} href={link.url} target="_blank" rel="noreferrer" style={{
              textDecoration: 'none', color: 'inherit',
              background: palette.surface, borderRadius: 14,
              padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 14,
              boxShadow: `0 1px 0 ${palette.ink}10, 0 2px 8px ${palette.ink}08`,
              border: `1px solid ${palette.ink}08`,
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10, flexShrink: 0,
                background: palette.tag, display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: palette.ink,
              }}>
                <Ico size={18} stroke={palette.ink} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 15, color: palette.ink, lineHeight: 1.2 }}>{link.title}</div>
                {link.subtitle && (
                  <div style={{ fontSize: 12, color: palette.ink2, marginTop: 2, lineHeight: 1.3 }}>{link.subtitle}</div>
                )}
              </div>
              <I.arrowRight size={16} stroke={palette.ink2} />
            </a>
          );
        })}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// STYLE 2 — BENTO (modular grid with varied sizes)
// Pattern: alternates between solo full-width and pairs. The "featured"
// flag on a link makes it span 2 cols.
// ────────────────────────────────────────────────────────────
function StyleBento({ profile, links, palette }) {
  const I = window.Icon;

  // Build a layout sequence: featured items go full-width; non-featured
  // items pair up two-per-row. We'll precompute rows.
  const rows = [];
  let pair = [];
  links.forEach(l => {
    if (l.featured) {
      if (pair.length) { rows.push(pair); pair = []; }
      rows.push([l]);
    } else {
      pair.push(l);
      if (pair.length === 2) { rows.push(pair); pair = []; }
    }
  });
  if (pair.length) rows.push(pair);

  return (
    <div style={{ minHeight: '100%', color: palette.ink }}>
      <ProfileHeader profile={profile} palette={palette} dense />
      <div style={{ padding: '4px 16px 80px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {rows.map((row, ri) => (
          <div key={ri} style={{ display: 'grid', gridTemplateColumns: row.length === 1 ? '1fr' : '1fr 1fr', gap: 12 }}>
            {row.map(link => {
              const Ico = I[link.icon] || I.link;
              const full = row.length === 1;
              return (
                <a key={link.id} href={link.url} target="_blank" rel="noreferrer" style={{
                  textDecoration: 'none', color: 'inherit',
                  background: palette.surface,
                  borderRadius: 18,
                  padding: full ? '20px 20px 22px' : '16px 16px 18px',
                  minHeight: full ? 120 : 130,
                  display: 'flex', flexDirection: 'column',
                  border: `1px solid ${palette.ink}10`,
                  boxShadow: `0 1px 0 ${palette.ink}06`,
                  position: 'relative', overflow: 'hidden',
                }}>
                  {/* Icon chip */}
                  <div style={{
                    width: full ? 40 : 34, height: full ? 40 : 34, borderRadius: 12,
                    background: palette.tag, display: 'flex', alignItems: 'center', justifyContent: 'center',
                    marginBottom: full ? 14 : 10,
                  }}>
                    <Ico size={full ? 20 : 18} stroke={palette.ink} />
                  </div>
                  <div style={{
                    fontWeight: 600, fontSize: full ? 17 : 14, color: palette.ink,
                    lineHeight: 1.2, letterSpacing: '-0.01em', textWrap: 'balance',
                  }}>{link.title}</div>
                  {link.subtitle && (
                    <div style={{
                      fontSize: full ? 13 : 11.5, color: palette.ink2,
                      marginTop: full ? 6 : 4, lineHeight: 1.35,
                    }}>{link.subtitle}</div>
                  )}
                  <div style={{ flex: 1 }} />
                  <div style={{
                    marginTop: 10, fontSize: 12, fontWeight: 600,
                    color: palette.accent, display: 'flex', alignItems: 'center', gap: 4,
                  }}>
                    {link.price ? formatPrice(link.price) : 'Abrir'}
                    <I.arrowRight size={13} stroke={palette.accent} />
                  </div>
                </a>
              );
            })}
          </div>
        ))}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// STYLE 3 — CATÁLOGO (e-commerce style cards with price + CTA)
// ────────────────────────────────────────────────────────────
function StyleCatalog({ profile, links, palette }) {
  const I = window.Icon;
  return (
    <div style={{ minHeight: '100%', color: palette.ink }}>
      <ProfileHeader profile={profile} palette={palette} dense />
      <div style={{ padding: '8px 16px 80px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {links.map(link => {
          const Ico = I[link.icon] || I.link;
          const hash = [...(link.title || 'x')].reduce((a, c) => a + c.charCodeAt(0), 0);
          const h1 = hash % 360, h2 = (hash + 60) % 360;
          return (
            <a key={link.id} href={link.url} target="_blank" rel="noreferrer" style={{
              textDecoration: 'none', color: 'inherit',
              background: palette.surface, borderRadius: 16, overflow: 'hidden',
              border: `1px solid ${palette.ink}10`,
              display: 'flex', flexDirection: 'column',
              boxShadow: `0 1px 0 ${palette.ink}06`,
            }}>
              {/* Image block */}
              <div style={{
                height: 156, position: 'relative',
                background: link.image
                  ? undefined
                  : `linear-gradient(135deg, oklch(0.88 0.08 ${h1}), oklch(0.72 0.13 ${h2}))`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                overflow: 'hidden',
              }}>
                {link.image ? (
                  <img src={link.image} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                ) : (
                  <div style={{
                    width: 56, height: 56, borderRadius: '50%',
                    background: 'rgba(255,255,255,0.32)', backdropFilter: 'blur(6px)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <Ico size={26} stroke="#fff" />
                  </div>
                )}
                {link.tag && (
                  <div style={{
                    position: 'absolute', top: 10, left: 10,
                    background: palette.surface, color: palette.ink,
                    padding: '4px 10px', borderRadius: 999,
                    fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase',
                  }}>{link.tag}</div>
                )}
              </div>
              <div style={{ padding: '14px 16px 16px' }}>
                <div style={{ fontWeight: 700, fontSize: 16, color: palette.ink, lineHeight: 1.2, letterSpacing: '-0.01em' }}>
                  {link.title}
                </div>
                {link.subtitle && (
                  <div style={{ fontSize: 13, color: palette.ink2, marginTop: 4, lineHeight: 1.4 }}>
                    {link.subtitle}
                  </div>
                )}
                <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
                  {link.price ? (
                    <div style={{ fontWeight: 700, fontSize: 18, color: palette.ink, letterSpacing: '-0.01em' }}>
                      {formatPrice(link.price)}
                    </div>
                  ) : (
                    <div style={{ fontWeight: 600, fontSize: 13, color: palette.ink2 }}>Gratuito</div>
                  )}
                  <div style={{ flex: 1 }} />
                  <div style={{
                    background: palette.cta, color: palette.ctaInk,
                    padding: '9px 16px', borderRadius: 999,
                    fontSize: 13, fontWeight: 600,
                    display: 'flex', alignItems: 'center', gap: 5,
                  }}>
                    {link.cta || (link.price ? 'Comprar' : 'Acessar')}
                    <I.arrowRight size={13} stroke={palette.ctaInk} />
                  </div>
                </div>
              </div>
            </a>
          );
        })}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Public page (dispatcher) — wraps style with optional bg image
// ────────────────────────────────────────────────────────────
function PublicPage({ profile, links, style, paletteId, background, customColors }) {
  const palette = paletteId === 'custom' ? getCustomPalette(customColors) : (PALETTES[paletteId] || PALETTES.cream);
  const props = { profile, links, palette };
  let inner;
  if (style === 'bento') inner = <StyleBento {...props} />;
  else if (style === 'catalog') inner = <StyleCatalog {...props} />;
  else inner = <StyleClassic {...props} />;

  const hasImage = background && background.image;
  return (
    <div style={{ position: 'relative', minHeight: '100vh', background: palette.bg, color: palette.ink }}>
      {hasImage && (
        <div aria-hidden style={{
          position: 'absolute', inset: 0, zIndex: 0,
          backgroundImage: `url(${background.image})`,
          backgroundSize: 'cover', backgroundPosition: 'center',
          opacity: background.opacity ?? 0.5,
          filter: `blur(${background.blur ?? 0}px) saturate(1.15)`,
          pointerEvents: 'none',
        }} />
      )}
      <div style={{ position: 'relative', zIndex: 1 }}>
        {inner}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Custom palette helpers
// ────────────────────────────────────────────────────────────
function getCustomPalette(c) {
  c = c || {};
  const bg = c.bg || '#f3eee4';
  const surface = c.surface || '#ffffff';
  const ink = c.ink || '#1f1b14';
  const accent = c.accent || '#1f1b14';
  return {
    name: 'Personalizado', bg, surface, ink,
    ink2: mixHex(ink, bg, 0.45),
    accent, cta: accent, ctaInk: getContrastColor(accent),
    tag: mixHex(surface, ink, 0.08),
  };
}
function getContrastColor(hex) {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
  return lum > 0.55 ? '#1a1a1a' : '#ffffff';
}
function mixHex(a, b, ratio) {
  const ar = parseInt(a.slice(1,3),16), ag = parseInt(a.slice(3,5),16), ab = parseInt(a.slice(5,7),16);
  const br = parseInt(b.slice(1,3),16), bg = parseInt(b.slice(3,5),16), bb = parseInt(b.slice(5,7),16);
  const r = Math.round(ar * (1-ratio) + br * ratio);
  const g = Math.round(ag * (1-ratio) + bg * ratio);
  const bl = Math.round(ab * (1-ratio) + bb * ratio);
  return '#' + [r,g,bl].map(x => x.toString(16).padStart(2,'0')).join('');
}

// ────────────────────────────────────────────────────────────
// Helpers
// ────────────────────────────────────────────────────────────
function formatPrice(p) {
  if (!p && p !== 0) return '';
  if (typeof p === 'string') return p;
  return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(p);
}

Object.assign(window, {
  PALETTES, PublicPage, formatPrice, Avatar, getCustomPalette, getContrastColor, mixHex,
});
