// 共通UIプリミティブ + Phone枠

// イニシャル円アバター (絵文字なし)
function Avatar({ theme, name, size = 44, accent }) {
  const initial = (name || '?').trim()[0] || '?';
  // 名前ハッシュで色相を分散
  let hash = 0;
  for (const c of (name || '?')) hash = (hash * 31 + c.charCodeAt(0)) >>> 0;
  const palette = [theme.primary, theme.accent, theme.success, theme.textMuted];
  const bg = accent ? theme.primary : palette[hash % palette.length];
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: bg, color: '#fff',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.44, fontWeight: 800,
      fontFamily: theme.headingFont,
      flexShrink: 0, letterSpacing: -0.5,
      lineHeight: 1,
    }}>{initial}</div>
  );
}

// モバイル画面の枠
function Phone({ theme, children, style }) {
  return (
    <div style={{
      width: '100%', height: '100%',
      background: theme.bg,
      color: theme.text,
      fontFamily: theme.bodyFont,
      overflow: 'auto',
      position: 'relative',
      ...style,
    }}>
      {children}
    </div>
  );
}

// 装飾的な背景パターン (テーマごと)
function Pattern({ theme, intensity = 1 }) {
  if (theme.pattern === 'natsu') {
    // 提灯ドット風
    return (
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none', opacity: 0.6 * intensity }}>
        <defs>
          <pattern id={`p-natsu-${theme.id}`} x="0" y="0" width="48" height="48" patternUnits="userSpaceOnUse">
            <circle cx="24" cy="24" r="2" fill={theme.accent} opacity="0.25" />
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill={`url(#p-natsu-${theme.id})`} />
      </svg>
    );
  }
  if (theme.pattern === 'ise') {
    // 波模様
    return (
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none', opacity: 0.5 * intensity }}>
        <defs>
          <pattern id={`p-ise-${theme.id}`} x="0" y="0" width="60" height="20" patternUnits="userSpaceOnUse">
            <path d="M0 10 Q15 0 30 10 T60 10" stroke={theme.primary} strokeWidth="1" fill="none" opacity="0.18" />
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill={`url(#p-ise-${theme.id})`} />
      </svg>
    );
  }
  // shinrai: 細い格子
  return (
    <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none', opacity: 0.4 * intensity }}>
      <defs>
        <pattern id={`p-shi-${theme.id}`} x="0" y="0" width="40" height="40" patternUnits="userSpaceOnUse">
          <path d="M40 0 L0 0 0 40" stroke={theme.primary} strokeWidth="0.5" fill="none" opacity="0.15" />
        </pattern>
      </defs>
      <rect width="100%" height="100%" fill={`url(#p-shi-${theme.id})`} />
    </svg>
  );
}

// チップ (タグ)
function Chip({ theme, children, color, active, onClick, size = 'md' }) {
  const bg = active ? (color || theme.primary) : theme.chipBg;
  const fg = active ? '#fff' : (color || theme.chipFg);
  const padY = size === 'sm' ? 4 : 6;
  const padX = size === 'sm' ? 8 : 12;
  const fs = size === 'sm' ? 11 : 12.5;
  return (
    <span onClick={onClick}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 4,
        padding: `${padY}px ${padX}px`,
        background: bg, color: fg,
        fontSize: fs, fontWeight: 600,
        borderRadius: 999,
        cursor: onClick ? 'pointer' : 'default',
        border: active ? 'none' : `1px solid ${theme.border}`,
        userSelect: 'none', whiteSpace: 'nowrap',
        transition: 'all .15s',
      }}>
      {children}
    </span>
  );
}

// ボタン
function Btn({ theme, children, onClick, variant = 'primary', size = 'md', fullWidth, style }) {
  const base = {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
    border: 'none', cursor: 'pointer', fontWeight: 700,
    fontFamily: theme.bodyFont, transition: 'all .15s',
    width: fullWidth ? '100%' : 'auto',
  };
  const sizes = {
    sm: { padding: '8px 14px', fontSize: 13, borderRadius: theme.radius - 2 },
    md: { padding: '12px 20px', fontSize: 14.5, borderRadius: theme.radius },
    lg: { padding: '16px 24px', fontSize: 16, borderRadius: theme.radiusLg },
  };
  const variants = {
    primary: { background: theme.primary, color: theme.primaryFg, boxShadow: `0 2px 0 ${theme.text}10` },
    ghost: { background: 'transparent', color: theme.primary, border: `1.5px solid ${theme.primary}` },
    soft: { background: theme.primarySoft, color: theme.primary },
    plain: { background: theme.surface, color: theme.text, border: `1px solid ${theme.border}` },
  };
  return (
    <button onClick={onClick} style={{ ...base, ...sizes[size], ...variants[variant], ...style }}>
      {children}
    </button>
  );
}

// セクション見出し
function SectionTitle({ theme, kicker, children, align = 'left' }) {
  return (
    <div style={{ marginBottom: 12, textAlign: align }}>
      {kicker && (
        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1.5,
          color: theme.primary, marginBottom: 4 }}>
          {kicker}
        </div>
      )}
      <h2 style={{
        margin: 0, fontFamily: theme.headingFont,
        fontSize: 17, fontWeight: 700, color: theme.text,
      }}>{children}</h2>
    </div>
  );
}

// カード
function Card({ theme, children, style, padding = 16 }) {
  return (
    <div style={{
      background: theme.surface,
      borderRadius: theme.radiusLg,
      border: `1px solid ${theme.border}`,
      padding,
      boxShadow: `0 1px 0 ${theme.text}05`,
      ...style,
    }}>
      {children}
    </div>
  );
}

// ステータスバー (モバイル用)
function StatusBar({ theme }) {
  return (
    <div style={{
      height: 32, padding: '0 18px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      fontSize: 13, fontWeight: 700, color: theme.text,
      fontFeatureSettings: '"tnum"',
    }}>
      <span>10:08</span>
      <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        <span style={{ fontSize: 10 }}>●●●●</span>
        <span style={{ fontSize: 11 }}>5G</span>
        <span style={{
          display: 'inline-block', width: 22, height: 11,
          border: `1.2px solid ${theme.text}`, borderRadius: 2,
          position: 'relative',
        }}>
          <span style={{
            position: 'absolute', inset: 1.5, background: theme.text,
            width: '70%', borderRadius: 1,
          }}></span>
        </span>
      </div>
    </div>
  );
}

// 棒グラフ (横向き)
function BarRow({ theme, label, value, max, color, sublabel }) {
  const pct = Math.max(0, Math.min(100, (value / max) * 100));
  return (
    <div style={{ marginBottom: 10 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: theme.text }}>{label}</span>
        <span style={{ fontSize: 12, color: theme.textMuted, fontFeatureSettings: '"tnum"' }}>
          {sublabel || `${value}人`}
        </span>
      </div>
      <div style={{ height: 8, background: theme.chipBg, borderRadius: 999, overflow: 'hidden' }}>
        <div style={{
          width: `${pct}%`, height: '100%',
          background: color || theme.primary, borderRadius: 999,
          transition: 'width .4s ease',
        }}></div>
      </div>
    </div>
  );
}

// ロゴ風タイトル (テーマごとに表情を変える)
function BrandMark({ theme, size = 'md' }) {
  const sz = size === 'sm' ? 28 : size === 'lg' ? 56 : 40;
  if (theme.pattern === 'natsu') {
    return (
      <div style={{
        width: sz, height: sz, borderRadius: '50%',
        background: `radial-gradient(circle at 35% 35%, ${theme.accent}, ${theme.primary})`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: '#fff', fontWeight: 900, fontSize: sz * 0.42,
        fontFamily: theme.headingFont,
        boxShadow: `0 2px 0 ${theme.text}15`,
      }}>三</div>
    );
  }
  if (theme.pattern === 'ise') {
    return (
      <div style={{
        width: sz, height: sz, borderRadius: theme.radius,
        background: theme.primary, color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontWeight: 900, fontSize: sz * 0.42,
        fontFamily: theme.headingFont, position: 'relative', overflow: 'hidden',
      }}>
        <svg style={{ position: 'absolute', inset: 0 }} viewBox="0 0 40 40">
          <path d={`M0 ${sz * 0.65} Q${sz * 0.25} ${sz * 0.5} ${sz * 0.5} ${sz * 0.65} T${sz} ${sz * 0.65} V${sz} H0 Z`}
            fill={theme.accent} opacity="0.5" />
        </svg>
        <span style={{ position: 'relative' }}>三</span>
      </div>
    );
  }
  return (
    <div style={{
      width: sz, height: sz, borderRadius: 4,
      background: theme.primary, color: theme.primaryFg,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontWeight: 900, fontSize: sz * 0.4,
      fontFamily: theme.headingFont, letterSpacing: -1,
      borderBottom: `3px solid ${theme.accent}`,
    }}>三</div>
  );
}

Object.assign(window, { Avatar, Phone, Pattern, Chip, Btn, SectionTitle, Card, StatusBar, BarRow, BrandMark });
