// ui.jsx — shared UI primitives & layout chrome

// ── Logo: monogram E+H + wordmark ───────────────────────────────
function Logo({ compact=false }) {
  return (
    <div className="flex items-center gap-2.5">
      <svg width="34" height="34" viewBox="0 0 40 40" aria-label="EnrollHub">
        <defs>
          <linearGradient id="logoGrad" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#D89AAA"/>
            <stop offset="100%" stopColor="#B5728C"/>
          </linearGradient>
        </defs>
        <rect x="0" y="0" width="40" height="40" rx="9" fill="url(#logoGrad)"/>
        {/* Stylised E + H monogram */}
        <g fill="none" stroke="#FCF7F6" strokeWidth="2.6" strokeLinecap="round">
          <path d="M11 11 L11 29" />
          <path d="M11 11 L20 11" />
          <path d="M11 20 L18 20" />
          <path d="M11 29 L20 29" />
          <path d="M26 11 L26 29" />
          <path d="M26 20 L31 20" strokeWidth="2.6"/>
        </g>
        <circle cx="31" cy="20" r="1.6" fill="#FCF7F6"/>
      </svg>
      {!compact && (
        <div className="leading-tight">
          <div className="text-[15px] font-semibold tracking-wide text-cream">EnrollHub</div>
          <div className="text-[10px] tracking-[0.18em] text-roselight/90">W NAIL SCHOOL</div>
        </div>
      )}
    </div>
  );
}

// ── Sidebar ─────────────────────────────────────────────────────
const NAV_ITEMS = [
  { id:'dashboard', label:'ダッシュボード', icon:'home',   screen:'dashboard' },
  { id:'students',  label:'生徒（カルテ）', icon:'users',  screen:'student' },
  { id:'schedule',  label:'予約・スケジュール', icon:'cal' },
  { id:'msg',       label:'メッセージ',     icon:'msg',   badge:7 },
  { id:'kpi',       label:'KPIレポート',    icon:'chart', screen:'kpi' },
  { id:'mobile',    label:'スマホ表示',     icon:'phone', screen:'mobile', spacer:true },
  { id:'settings',  label:'設定',          icon:'cog' },
];

function NavIcon({ name }) {
  const s = { stroke:'currentColor', fill:'none', strokeWidth:1.6, strokeLinecap:'round', strokeLinejoin:'round' };
  switch (name) {
    case 'home':  return <svg width="18" height="18" viewBox="0 0 24 24" {...s}><path d="M3 11l9-7 9 7"/><path d="M5 10v10h14V10"/></svg>;
    case 'users': return <svg width="18" height="18" viewBox="0 0 24 24" {...s}><circle cx="9" cy="8" r="3.2"/><circle cx="17" cy="9" r="2.5"/><path d="M3 20c.6-3.4 3-5.5 6-5.5s5.4 2.1 6 5.5"/><path d="M15 19c.4-2 1.7-3.4 4-3.4"/></svg>;
    case 'cal':   return <svg width="18" height="18" viewBox="0 0 24 24" {...s}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18"/></svg>;
    case 'msg':   return <svg width="18" height="18" viewBox="0 0 24 24" {...s}><path d="M21 12a8 8 0 1 1-3.6-6.7L21 4l-1 4.2A8 8 0 0 1 21 12z"/></svg>;
    case 'chart': return <svg width="18" height="18" viewBox="0 0 24 24" {...s}><path d="M4 20V8M10 20V4M16 20v-9M22 20H2"/></svg>;
    case 'phone': return <svg width="18" height="18" viewBox="0 0 24 24" {...s}><rect x="6" y="2.5" width="12" height="19" rx="2.5"/><path d="M11 18h2"/></svg>;
    case 'cog':   return <svg width="18" height="18" viewBox="0 0 24 24" {...s}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8L4.2 7a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1A2 2 0 1 1 19.7 7l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>;
    default: return null;
  }
}

function Sidebar({ current, onNav, mode='full' /* full|icons */ }) {
  const width = mode === 'icons' ? 64 : 220;
  return (
    <aside className="sb flex flex-col shrink-0" style={{ width }}>
      <div className={`px-${mode==='icons'?3:5} pt-5 pb-6`} style={{ paddingLeft: mode==='icons'? 14 : 18, paddingRight: mode==='icons'? 14 : 18 }}>
        <Logo compact={mode==='icons'} />
      </div>
      <nav className="flex-1 flex flex-col gap-0.5 px-2">
        {NAV_ITEMS.map(it => {
          const active = it.screen === current;
          const clickable = !!it.screen;
          return (
            <React.Fragment key={it.id}>
              {it.spacer && <div className="h-3" />}
              <button
                onClick={() => clickable && onNav(it.screen)}
                disabled={!clickable}
                className={`sb-item ${active?'active':''} group flex items-center gap-3 px-3 py-2.5 text-[12.5px] rounded-lg transition-colors ${mode==='icons'?'justify-center':''} ${clickable?'cursor-default':'opacity-60 cursor-not-allowed'}`}
                title={it.label}
                style={{ marginLeft: 0 }}
              >
                <NavIcon name={it.icon} />
                {mode!=='icons' && <span className="flex-1 text-left">{it.label}</span>}
                {mode!=='icons' && it.badge && (
                  <span className="text-[10px] num font-semibold bg-rose text-white px-1.5 rounded-full">{it.badge}</span>
                )}
              </button>
            </React.Fragment>
          );
        })}
      </nav>
      <div className="hairline-t mt-2 px-4 py-3.5 flex items-center gap-2.5" style={{ borderColor:'rgba(245,221,227,.12)' }}>
        <div className="avatar" style={{ background:'#D89AAA', color:'#FCF7F6' }}>校</div>
        {mode!=='icons' && (
          <div className="leading-tight">
            <div className="text-[12.5px] font-medium text-cream">デモ校長 さん</div>
            <div className="text-[10.5px] text-gold/70">校長 / 管理者ロール</div>
          </div>
        )}
      </div>
    </aside>
  );
}

// ── Top bar ─────────────────────────────────────────────────────
function TopBar({ school, onSchool, searchPlaceholder='生徒名・LINE名・電話で検索', alerts=3, breadcrumb }) {
  return (
    <header className="h-14 bg-white hairline-b flex items-center px-5 gap-4 sticky top-0 z-10">
      <div className="flex items-center gap-2">
        <span className="text-[11px] text-mute tracking-wide">校舎</span>
        <div className="relative">
          <select
            value={school}
            onChange={(e) => onSchool && onSchool(e.target.value)}
            className="appearance-none bg-cream2/60 hover:bg-cream2 text-[12.5px] font-medium text-ink pl-3 pr-8 py-1.5 rounded-md border border-line cursor-default"
          >
            {SCHOOLS.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
          <svg className="absolute right-2.5 top-2 pointer-events-none" width="10" height="10" viewBox="0 0 10 10"><path fill="#9B8E85" d="M0 2h10L5 8z"/></svg>
        </div>
        {breadcrumb && (
          <div className="ml-3 flex items-center gap-2 text-[11.5px] text-mute">
            <span>›</span><span className="text-ink2">{breadcrumb}</span>
          </div>
        )}
      </div>

      <div className="flex-1 max-w-2xl mx-2">
        <div className="relative">
          <svg className="absolute left-3 top-2.5" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#9B8E85" strokeWidth="1.8"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
          <input
            placeholder={searchPlaceholder}
            className="w-full text-[12.5px] pl-9 pr-3 py-2 rounded-md bg-cream2/60 hover:bg-cream2 focus:bg-white border border-line focus:border-gold outline-none placeholder:text-mute"
          />
        </div>
      </div>

      <button className="relative w-9 h-9 rounded-md hover:bg-cream2 flex items-center justify-center" title="通知">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#3D2B2B" strokeWidth="1.6"><path d="M6 8a6 6 0 1 1 12 0c0 5 2 7 2 7H4s2-2 2-7z"/><path d="M10 19a2 2 0 0 0 4 0"/></svg>
        {alerts > 0 && (
          <span className="absolute -top-0.5 -right-0.5 min-w-[18px] h-[18px] px-1 num text-[10px] font-semibold rounded-full bg-alert text-white flex items-center justify-center">{alerts}</span>
        )}
      </button>

      <div className="flex items-center gap-2 pl-2 pr-1 ml-1 border-l border-line">
        <div className="avatar" style={{ width:32, height:32, background:'#5D3848', color:'#FCF7F6' }}>校</div>
        <div className="hidden md:block leading-tight">
          <div className="text-[12px] font-medium">デモ校長</div>
          <div className="text-[10px] text-mute">校長</div>
        </div>
      </div>
    </header>
  );
}

// ── Status badge ────────────────────────────────────────────────
function StatusBadge({ s }) {
  const st = STATUS[s];
  if (!st) return null;
  return (
    <span className="bdg" style={{ background: st.bg, color: st.text }}>
      <span style={{ display:'inline-block', width:6, height:6, borderRadius:99, background: st.band }} />
      {st.label}
    </span>
  );
}

// ── Initial avatar (school colour band) ─────────────────────────
const SCHOOL_COLOURS = {
  umeda:'#D89AAA', kyobashi:'#B5728C', shinsai:'#C9A98C',
  namba:'#9A8EAA',  kobe:'#7A9F7E',     shinjuku:'#D6A172',
  kenshu:'#A89098',
};
function Avatar({ name, school, size=36 }) {
  // Take first kanji of family + first kanji of given → 2 chars
  const parts = (name || '').split(' ');
  const init = (parts[0]?.[0] || '') + (parts[1]?.[0] || '');
  const colour = SCHOOL_COLOURS[school] || '#C9A98C';
  return (
    <div className="avatar relative" style={{ width:size, height:size, fontSize: size*0.34 }}>
      <span>{init || '？'}</span>
      <span style={{
        position:'absolute', left:1, top:1, bottom:1, width:3, borderRadius:'99px 0 0 99px',
        background: colour,
      }}/>
    </div>
  );
}

// ── Section header ──────────────────────────────────────────────
function SectionHeader({ title, sub, right, icon }) {
  return (
    <div className="flex items-center justify-between mb-3">
      <div className="flex items-center gap-2">
        {icon && <div className="w-1 h-4 rounded-full bg-gold" />}
        <h3 className="text-[13px] font-semibold text-ink">{title}</h3>
        {sub && <span className="text-[11px] text-mute">— {sub}</span>}
      </div>
      {right}
    </div>
  );
}

// ── Small stat tile ─────────────────────────────────────────────
function StatTile({ label, value, suffix, delta, tone='default', icon, sub }) {
  const toneMap = {
    default: { bg:'#fff', accent:'#D89AAA', text:'#5D3848' },
    alert:   { bg:'#FBE9EE', accent:'#C9536A', text:'#A23A55' },
    ok:      { bg:'#E8EEE6', accent:'#7A9F7E', text:'#4F7559' },
    warn:    { bg:'#FAEEDC', accent:'#D6A172', text:'#86592E' },
  };
  const T = toneMap[tone] || toneMap.default;
  return (
    <div className="card relative overflow-hidden" style={{ background:T.bg }}>
      <div style={{ position:'absolute', left:0, top:0, bottom:0, width:3, background:T.accent }}/>
      <div className="px-5 py-4">
        <div className="flex items-center justify-between mb-1.5">
          <span className="text-[11.5px] font-medium text-mute">{label}</span>
          {icon}
        </div>
        <div className="flex items-baseline gap-1">
          <span className="num text-[30px] font-semibold leading-none" style={{ color:T.text }}>{value}</span>
          {suffix && <span className="text-[12px] text-mute font-medium">{suffix}</span>}
        </div>
        {(delta || sub) && (
          <div className="mt-2 text-[11px] text-mute flex items-center gap-1.5">
            {delta && (
              <span className={`num font-medium ${delta.startsWith('+') ? 'text-okgreen' : 'text-alert'}`}>{delta}</span>
            )}
            {sub && <span>{sub}</span>}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Logo, Sidebar, TopBar, StatusBadge, Avatar, SectionHeader, StatTile, NavIcon, NAV_ITEMS, SCHOOL_COLOURS });
