// chassis.jsx — shared "skin-able" components used across all paths.
// Every component takes `t` (the active theme/path) and renders accordingly.

// ────────────────────────────────────────────────────────────
// PhoneFrame — simple "card" shell w/ status bar + bottom-nav slot.
// 390 × 844 px (iPhone 14 design width). No iOS chrome bezel — we want
// the artboard to BE the phone since these are static mockups on a canvas.
// ────────────────────────────────────────────────────────────
function PhoneFrame({ t, children, statusDark = true, label }) {
  return (
    <div style={{
      width: 390, height: 844,
      background: t.bg, color: t.text, position: 'relative',
      fontFamily: t.fontBody, overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
      borderRadius: 0,
      WebkitFontSmoothing: 'antialiased',
    }}>
      <PhoneStatusBar t={t} dark={statusDark}/>
      <div style={{ flex: 1, minHeight: 0, position: 'relative', overflow: 'hidden' }}>
        {children}
      </div>
    </div>
  );
}

function PhoneStatusBar({ t, dark = true }) {
  const c = dark ? t.text : '#000';
  return (
    <div style={{
      height: 44, paddingTop: 14, display: 'flex', alignItems: 'center',
      justifyContent: 'space-between', padding: '14px 28px 0',
      fontFamily: t.fontBody, color: c, fontSize: 14, fontWeight: 600,
      letterSpacing: '-0.02em', flexShrink: 0,
    }}>
      <span>9:41</span>
      <div style={{ display:'flex', gap:6, alignItems:'center', opacity: 0.95 }}>
        <svg width="16" height="10" viewBox="0 0 16 10" fill={c}>
          <rect x="0" y="6" width="3" height="4" rx="0.5"/><rect x="4.5" y="4" width="3" height="6" rx="0.5"/>
          <rect x="9" y="2" width="3" height="8" rx="0.5"/><rect x="13.5" y="0" width="3" height="10" rx="0.5"/>
        </svg>
        <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke={c} strokeWidth="1.2">
          <path d="M1 4 Q7 -1 13 4"/><path d="M3 6 Q7 2 11 6"/><circle cx="7" cy="8.5" r="1" fill={c} stroke="none"/>
        </svg>
        <svg width="22" height="10" viewBox="0 0 22 10">
          <rect x="0.5" y="0.5" width="18" height="9" rx="2" fill="none" stroke={c} strokeOpacity="0.5"/>
          <rect x="2" y="2" width="15" height="6" rx="1" fill={c}/>
          <rect x="20" y="3" width="1.5" height="4" rx="0.5" fill={c} fillOpacity="0.5"/>
        </svg>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Title — adapts case + spacing per path.
// ────────────────────────────────────────────────────────────
function PathTitle({ t, children, size = 28, style = {} }) {
  return (
    <h1 style={{
      fontFamily: t.fontTitle, fontSize: size, fontWeight: 700,
      letterSpacing: t.titleSpace,
      textTransform: t.titleCase === 'upper' ? 'uppercase' : 'none',
      margin: 0, color: t.text, lineHeight: 1.05,
      ...style,
    }}>{children}</h1>
  );
}

// ────────────────────────────────────────────────────────────
// PerforatedEdge — for casual path & accents
// ────────────────────────────────────────────────────────────
function PerforatedEdge({ t, vertical=false, color }) {
  const c = color || t.bg;
  if (vertical) {
    return (
      <div style={{ position:'absolute', top:0, bottom:0, left:'50%', transform:'translateX(-50%)',
        width: 14, display:'flex', flexDirection:'column', justifyContent:'space-between', padding:'8px 0' }}>
        {Array.from({length: 22}).map((_,i)=>(
          <div key={i} style={{ width: 6, height: 6, borderRadius: '50%', background: c }}/>
        ))}
      </div>
    );
  }
  return (
    <div style={{ height: 14, display:'flex', justifyContent:'space-between', alignItems:'center', padding:'0 12px' }}>
      {Array.from({length: 32}).map((_,i)=>(
        <div key={i} style={{ width: 6, height: 6, borderRadius:'50%', background: c }}/>
      ))}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Stamp — three shapes (hex / flower / circle) per path
// ────────────────────────────────────────────────────────────
function StampShape({ t, filled, color, glyph, size = 56 }) {
  const fg = filled ? '#fff' : t.textDim;
  const bg = filled ? color : 'transparent';
  const border = filled ? color : t.line;
  const stroke = filled ? 0 : 1.5;

  if (t.stampShape === 'hex') {
    return (
      <svg width={size} height={size} viewBox="0 0 60 60">
        <polygon points="30,4 53,17 53,43 30,56 7,43 7,17"
          fill={bg} stroke={border} strokeWidth={stroke}/>
        {filled && (
          <polygon points="30,8 49,19 49,41 30,52 11,41 11,19"
            fill="none" stroke="rgba(255,255,255,0.3)" strokeWidth="1"/>
        )}
        <text x="30" y="36" textAnchor="middle" fill={fg}
              fontSize={filled ? 22 : 18}
              fontFamily={t.fontTitle} fontWeight="700">{glyph}</text>
      </svg>
    );
  }
  if (t.stampShape === 'flower') {
    return (
      <svg width={size} height={size} viewBox="0 0 60 60">
        <path d="M30 6 C36 6 40 10 40 16 C46 16 50 20 50 26 C50 32 46 36 40 36 C40 42 36 46 30 46 C24 46 20 42 20 36 C14 36 10 32 10 26 C10 20 14 16 20 16 C20 10 24 6 30 6 Z"
          transform="translate(0 4)"
          fill={bg} stroke={border} strokeWidth={stroke}/>
        <text x="30" y="36" textAnchor="middle" fill={fg}
              fontSize={filled ? 22 : 18}
              fontFamily={t.fontTitle} fontWeight="700">{glyph}</text>
      </svg>
    );
  }
  // circle (casual)
  return (
    <svg width={size} height={size} viewBox="0 0 60 60">
      <circle cx="30" cy="30" r="25" fill={bg} stroke={border} strokeWidth={stroke}/>
      {filled && <circle cx="30" cy="30" r="21" fill="none" stroke="rgba(255,255,255,0.25)" strokeWidth="1"/>}
      <text x="30" y="37" textAnchor="middle" fill={fg}
            fontSize={filled ? 22 : 18}
            fontFamily={t.fontTitle} fontWeight="700">{glyph}</text>
    </svg>
  );
}

// ────────────────────────────────────────────────────────────
// StampGrid — 7 floor stamps. Renders per-path layout treatment.
// ────────────────────────────────────────────────────────────
function StampGrid({ t, stamps /* Set<string> */, compact = false }) {
  const sz = compact ? 48 : 60;
  return (
    <div style={{
      display:'grid',
      gridTemplateColumns:'repeat(7, 1fr)',
      gap: compact ? 6 : 10,
      alignItems:'center',
    }}>
      {FLOORS.map(f => {
        const has = stamps.has(f.code);
        return (
          <div key={f.code} style={{
            display:'flex', flexDirection:'column', alignItems:'center', gap: 4,
          }}>
            <StampShape t={t} filled={has} color={f.color} glyph={f.code} size={sz}/>
            {!compact && (
              <span style={{
                fontFamily: t.fontMono, fontSize: 9, color: t.textDim,
                letterSpacing: '0.06em', textTransform:'uppercase',
              }}>{f.name.split(' ')[0]}</span>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// BottomNav — 5 tabs across all paths
// ────────────────────────────────────────────────────────────
const NAV_ITEMS = [
  { id:'passport', label:'Pass',     icon:'pass'   },
  { id:'quests',   label:'Quests',   icon:'quest'  },
  { id:'scan',     label:'Scan',     icon:'scan'   },
  { id:'map',      label:'Map',      icon:'map'    },
  { id:'more',     label:'More',     icon:'more'   },
];

function NavIcon({ name, color, size=22, active=false }) {
  const sw = active ? 2 : 1.6;
  if (name==='pass') return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={sw}>
      <rect x="3" y="6" width="18" height="13" rx="2"/>
      <path d="M3 11h18" strokeDasharray="2 2"/>
      <circle cx="8" cy="15" r="1.5" fill={active?color:'none'}/>
    </svg>
  );
  if (name==='quest') return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={sw}>
      <path d="M5 4h11l3 3v13H5z"/><path d="M9 12h7M9 16h5M9 8h4"/>
    </svg>
  );
  if (name==='scan') return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={sw}>
      <path d="M4 8V5a1 1 0 011-1h3M16 4h3a1 1 0 011 1v3M20 16v3a1 1 0 01-1 1h-3M8 20H5a1 1 0 01-1-1v-3"/>
      <rect x="8" y="8" width="8" height="8" fill={active?color:'none'} stroke={color}/>
    </svg>
  );
  if (name==='map') return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={sw}>
      <path d="M9 3l-6 3v15l6-3 6 3 6-3V3l-6 3z"/><path d="M9 3v15M15 6v15"/>
    </svg>
  );
  if (name==='more') return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
      <circle cx="6" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="18" cy="12" r="1.6"/>
    </svg>
  );
  return null;
}

function BottomNav({ t, active='passport', onTab }) {
  return (
    <div style={{
      position:'absolute', left:0, right:0, bottom:0,
      paddingBottom: 22,
      background: t.edge==='angular'
        ? `linear-gradient(180deg, transparent, ${t.bgDeep} 30%)`
        : `linear-gradient(180deg, transparent, ${t.bgDeep} 25%)`,
    }}>
      <div style={{
        margin:'0 16px',
        background: t.surface,
        border: `1px solid ${t.line2}`,
        borderRadius: t.edge==='angular' ? 4 : t.edge==='rounded' ? 24 : 14,
        height: 64, display:'flex', alignItems:'center', justifyContent:'space-around',
        padding: '0 8px',
        boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
      }}>
        {NAV_ITEMS.map(item => {
          const isActive = active === item.id;
          const isScan = item.id === 'scan';
          if (isScan) {
            return (
              <button key={item.id} onClick={()=>onTab&&onTab(item.id)} style={{
                width:48, height:48, borderRadius: t.edge==='angular' ? 4 : '50%',
                background: t.accent, border:'none', cursor:'pointer', marginTop:-22,
                display:'flex', alignItems:'center', justifyContent:'center',
                boxShadow: `0 8px 18px ${t.accent}55, 0 0 0 4px ${t.bg}`,
              }}>
                <NavIcon name="scan" color="#fff" size={24} active/>
              </button>
            );
          }
          const c = isActive ? t.accent : t.textMute;
          return (
            <button key={item.id} onClick={()=>onTab&&onTab(item.id)} style={{
              background:'none', border:'none', cursor:'pointer',
              display:'flex', flexDirection:'column', alignItems:'center', gap:4, padding:6,
            }}>
              <NavIcon name={item.icon} color={c} active={isActive}/>
              <span style={{
                fontSize: 10, fontFamily: t.fontBody, color: c,
                letterSpacing: t.titleCase==='upper' ? '0.1em' : '0',
                textTransform: t.titleCase==='upper' ? 'uppercase' : 'none',
                fontWeight: isActive ? 600 : 500,
              }}>{item.label}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Card — base surface w/ path-specific edge treatment
// ────────────────────────────────────────────────────────────
function Card({ t, children, style = {}, accent }) {
  const styleByEdge = {
    angular: {
      background: t.surface,
      border: `1px solid ${t.line}`,
      borderRadius: 4,
      // chamfer corners w/ clip-path
      clipPath: 'polygon(0 0, calc(100% - 12px) 0, 100% 12px, 100% 100%, 12px 100%, 0 calc(100% - 12px))',
    },
    rounded: {
      background: t.surface,
      border: `1px solid ${t.line2}`,
      borderRadius: 20,
    },
    crisp: {
      background: t.surface,
      border: `1px solid ${t.line2}`,
      borderRadius: 10,
    },
  };
  return (
    <div style={{
      ...styleByEdge[t.edge],
      position: 'relative',
      ...style,
    }}>
      {accent && t.edge==='angular' && (
        <div style={{
          position:'absolute', top:0, left:0, width:3, height:'100%',
          background: t.accent,
        }}/>
      )}
      {children}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// SectionLabel — small kicker label per path
// ────────────────────────────────────────────────────────────
function SectionLabel({ t, children, color }) {
  return (
    <div style={{
      fontFamily: t.fontMono, fontSize: 10,
      color: color || t.textMute,
      letterSpacing: '0.18em', textTransform: 'uppercase',
      display:'flex', alignItems:'center', gap: 6,
    }}>
      <div style={{ width: 12, height: 1, background: color || t.textMute, opacity:0.5 }}/>
      {children}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// HuaweiBadge — sponsor strip / accent
// ────────────────────────────────────────────────────────────
function HuaweiBadge({ t, size='sm', show=true }) {
  if (!show) return null;
  const fs = size==='sm' ? 9 : 11;
  const logoH = size==='sm' ? 11 : 14;
  // Use real Huawei wordmark — invert on dark themes so the red flame stays
  // recognizable but the wordmark renders white.
  const isDark = t.mode !== 'light';
  return (
    <div style={{
      display:'inline-flex', alignItems:'center', gap:8,
      fontFamily: t.fontMono, fontSize: fs, color: t.textMute,
      letterSpacing:'0.12em', textTransform:'uppercase',
    }}>
      <span>Powered by</span>
      <img
        src={isDark ? 'assets/huawei-logo-dark.svg' : 'assets/huawei-logo.svg'}
        alt="HUAWEI"
        style={{ height: logoH, width:'auto', display:'block' }}
      />
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// PocaLockup — official POCA wordmark image + "RALLY" line below.
// Use in place of any text "Echoria Rally" / "POCA Rally" lockup.
// `size` is the height of the POCA wordmark in px.
// ────────────────────────────────────────────────────────────
function PocaLockup({ t, size = 92, align='left', stack=true, showRally=true, glow=true }) {
  const labelSize = Math.max(11, Math.round(size * 0.16));
  const gap = Math.round(size * 0.08);
  return (
    <div style={{
      display:'inline-flex', flexDirection: stack ? 'column' : 'row',
      alignItems: align==='center' ? 'center' : 'flex-start',
      gap,
    }}>
      <img
        src="assets/poca-logo.png"
        alt="POCA"
        style={{
          height: size, width:'auto', display:'block',
          // The supplied logo has a soft holographic glow — drop a subtle
          // accent shadow so it integrates with each path's color identity.
          filter: glow ? `drop-shadow(0 0 ${size*0.18}px ${(t?.accent2||'#5eeaff')}66)` : 'none',
        }}
      />
      {showRally && (
        <div style={{
          fontFamily: t?.fontTitle || 'Orbitron, sans-serif',
          fontSize: labelSize, fontWeight: 800,
          letterSpacing: '0.42em',
          color: t?.text || '#fff',
          textTransform: 'uppercase',
          paddingLeft: stack ? 4 : 0,
        }}>Rally</div>
      )}
    </div>
  );
}

// expose
Object.assign(window, {
  PhoneFrame, PhoneStatusBar, PathTitle, PerforatedEdge,
  StampShape, StampGrid, BottomNav, Card, SectionLabel, HuaweiBadge, PocaLockup,
  NAV_ITEMS, NavIcon,
});
