// 하루결 — 공유 UI 컴포넌트

const IMG = {
  morning: 'https://images.unsplash.com/photo-1495231916356-a86217efff12?auto=format&fit=crop&w=900&q=80',
  tea:     'https://images.unsplash.com/photo-1576092768241-dec231879fc3?auto=format&fit=crop&w=900&q=80',
  meal:    'https://images.unsplash.com/photo-1547592180-85f173990554?auto=format&fit=crop&w=900&q=80',
  window:  'https://images.unsplash.com/photo-1490730141103-6cac27aaab94?auto=format&fit=crop&w=900&q=80',
  flower:  'https://images.unsplash.com/photo-1490750967868-88aa4486c946?auto=format&fit=crop&w=900&q=80',
};

// ── 화면 헤더 (상단 상태바 영역 포함) ─────────────────────
function ScreenHeader({ title, sub, action, back, onBack, dark = false }) {
  return (
    <div style={{ padding: '54px 22px 12px', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12 }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        {back && (
          <button onClick={onBack} aria-label="뒤로" style={{
            width: 38, height: 38, borderRadius: '50%',
            background: dark ? 'rgba(255,253,247,0.16)' : 'var(--hg-surface)',
            border: dark ? 'none' : '1px solid var(--hg-line-soft)',
            display: 'grid', placeItems: 'center', marginBottom: 12,
            color: dark ? '#fff' : 'var(--hg-ink)', fontSize: 18,
          }}>‹</button>
        )}
        {sub && <div style={{ fontSize: 13, color: dark ? 'rgba(255,253,247,0.7)' : 'var(--hg-muted)', fontWeight: 500, marginBottom: 4 }}>{sub}</div>}
        <div className="hg-serif" style={{
          fontSize: 28, fontWeight: 600, letterSpacing: '-0.025em', lineHeight: 1.2,
          color: dark ? '#fff' : 'var(--hg-ink)', textWrap: 'pretty',
        }}>{title}</div>
      </div>
      {action}
    </div>
  );
}

// ── 패널 카드 ─────────────────────────────────────────
function Panel({ children, style, ...p }) {
  return (
    <div {...p} style={{
      background: 'var(--hg-surface)',
      border: '1px solid var(--hg-line-soft)',
      borderRadius: 22,
      padding: 18,
      ...style,
    }}>{children}</div>
  );
}

// ── Eyebrow 작은 캡션 ─────────────────────────────────
function Eyebrow({ children, color = 'var(--hg-clay)', style }) {
  return (
    <div style={{
      fontSize: 11, fontWeight: 700, letterSpacing: '0.08em',
      textTransform: 'uppercase', color, marginBottom: 6,
      ...style,
    }}>{children}</div>
  );
}

// ── 칩 ──────────────────────────────────────────────
function Chip({ children, color = 'var(--hg-clay)', bg = 'var(--hg-clay-tint)', style }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: '4px 10px', borderRadius: 999,
      background: bg, color, fontSize: 11, fontWeight: 700, letterSpacing: '-0.01em',
      whiteSpace: 'nowrap',
      ...style,
    }}>{children}</span>
  );
}

// ── 체크박스 ──────────────────────────────────────────
function Checkbox({ checked, onClick, size = 22 }) {
  // 클릭 핸들러가 있으면 버튼, 없으면 단순 표시(상위 버튼이 처리)
  const Tag = onClick ? 'button' : 'span';
  return (
    <Tag onClick={onClick} aria-pressed={onClick ? checked : undefined} role={onClick ? undefined : 'checkbox'} aria-checked={!onClick ? checked : undefined} style={{
      width: size, height: size, borderRadius: size * 0.32,
      background: checked ? 'var(--hg-clay)' : 'transparent',
      border: checked ? '1.5px solid var(--hg-clay)' : '1.5px solid var(--hg-line)',
      display: 'inline-grid', placeItems: 'center', flexShrink: 0, padding: 0,
      transition: 'all 160ms',
      ...(onClick ? {} : { pointerEvents: 'none' }),
    }}>
      {checked && (
        <svg width={size * 0.55} height={size * 0.55} viewBox="0 0 12 12" fill="none">
          <path d="M2 6.5L5 9l5-6" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      )}
    </Tag>
  );
}

// ── 무드 이미지 ──────────────────────────────────────
function MoodImage({ src, alt, style }) {
  return (
    <div style={{
      backgroundImage: `url("${src}")`,
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      ...style,
    }} role="img" aria-label={alt} />
  );
}

// ── FAB ──────────────────────────────────────────────
function FAB({ onClick, label = '추가', color = 'var(--hg-clay)' }) {
  return (
    <button onClick={onClick} aria-label={label} style={{
      width: 38, height: 38, borderRadius: '50%',
      background: color, color: '#fff',
      fontSize: 20, fontWeight: 300, display: 'grid', placeItems: 'center',
      boxShadow: '0 4px 12px rgba(181,117,90,0.32)',
    }}>＋</button>
  );
}

// ── 모달 시트 ────────────────────────────────────────
function Sheet({ title, onClose, children, footer }) {
  return (
    <div className="hg-overlay" onClick={(e) => { if (e.target.classList.contains('hg-overlay')) onClose(); }}>
      <div className="hg-sheet" role="dialog" aria-modal="true">
        <div className="hg-sheet__handle" />
        {title && (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
            <div className="hg-serif" style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>{title}</div>
            <button onClick={onClose} aria-label="닫기" style={{
              width: 32, height: 32, borderRadius: '50%',
              background: 'var(--hg-bg-deeper)', color: 'var(--hg-muted)',
              fontSize: 16, display: 'grid', placeItems: 'center',
            }}>✕</button>
          </div>
        )}
        {children}
        {footer && <div style={{ marginTop: 18 }}>{footer}</div>}
      </div>
    </div>
  );
}

// ── Primary Button ────────────────────────────────────
function PrimaryButton({ children, onClick, disabled, color = 'var(--hg-clay)', shadow = '0 8px 20px rgba(181,117,90,0.28)' }) {
  return (
    <button onClick={onClick} disabled={disabled} style={{
      width: '100%', minHeight: 54,
      background: disabled ? 'var(--hg-line)' : color, color: '#fff',
      fontSize: 15, fontWeight: 700, letterSpacing: '-0.02em',
      borderRadius: 18,
      boxShadow: disabled ? 'none' : shadow,
      opacity: disabled ? 0.6 : 1,
    }}>{children}</button>
  );
}

// ── 하단 탭바 ─────────────────────────────────────────
function BottomNav({ active, mode = 'patient', onChange }) {
  const items = mode === 'patient' ? [
    { id: 'home',     label: '오늘',   icon: 'home' },
    { id: 'schedule', label: '일정',   icon: 'cal' },
    { id: 'meal',     label: '식사',   icon: 'meal' },
    { id: 'symptom',  label: '증상',   icon: 'heart' },
    { id: 'more',     label: '더보기', icon: 'more' },
  ] : [
    { id: 'cg-home',    label: '오늘',     icon: 'home' },
    { id: 'cg-monitor', label: '환자 일지', icon: 'pulse' },
    { id: 'cg-visit',   label: '동행',     icon: 'cal' },
    { id: 'cg-more',    label: '더보기',   icon: 'more' },
  ];

  return (
    <div style={{
      position: 'sticky', bottom: 0, left: 0, right: 0,
      marginTop: 'auto',
      paddingBottom: 'calc(20px + env(safe-area-inset-bottom))',
      paddingTop: 10, paddingLeft: 12, paddingRight: 12,
      background: 'rgba(251, 246, 236, 0.94)',
      backdropFilter: 'blur(20px) saturate(160%)',
      WebkitBackdropFilter: 'blur(20px) saturate(160%)',
      borderTop: '0.5px solid var(--hg-line-soft)',
      display: 'flex', justifyContent: 'space-around',
      zIndex: 100,
    }}>
      {items.map((it) => {
        const on = it.id === active;
        return (
          <button key={it.id} onClick={() => onChange(it.id)} style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            color: on ? 'var(--hg-clay-dark)' : 'var(--hg-muted)',
            fontSize: 11, fontWeight: on ? 700 : 500, letterSpacing: '-0.02em',
            minWidth: 50, padding: '4px 2px',
          }}>
            <NavIcon name={it.icon} active={on} />
            <span>{it.label}</span>
          </button>
        );
      })}
    </div>
  );
}

function NavIcon({ name, active }) {
  const c = active ? 'var(--hg-clay-dark)' : 'var(--hg-muted)';
  const sw = active ? 2 : 1.6;
  const fill = active ? 'var(--hg-clay-tint)' : 'none';
  if (name === 'home') return <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><path d="M3 9.5L11 3l8 6.5V18a1 1 0 01-1 1h-4v-6h-6v6H4a1 1 0 01-1-1V9.5z" stroke={c} strokeWidth={sw} strokeLinejoin="round" fill={fill}/></svg>;
  if (name === 'cal')  return <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><rect x="3" y="5" width="16" height="14" rx="2.5" stroke={c} strokeWidth={sw} fill={fill}/><path d="M3 9h16M8 3v4M14 3v4" stroke={c} strokeWidth={sw} strokeLinecap="round"/></svg>;
  if (name === 'meal') return <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><path d="M6 4v7a3 3 0 003 3v5M9 4v7M14 4c-1.5 1-2 3-2 5s1 4 2 4v6" stroke={c} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round"/></svg>;
  if (name === 'heart')return <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><path d="M11 18s-7-4.2-7-9.5C4 5.5 6.5 4 8.5 4c1.4 0 2.3.6 2.5 1 .2-.4 1.1-1 2.5-1C15.5 4 18 5.5 18 8.5 18 13.8 11 18 11 18z" stroke={c} strokeWidth={sw} strokeLinejoin="round" fill={fill}/></svg>;
  if (name === 'pulse')return <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><path d="M2 11h4l2-5 3 10 3-7 2 2h4" stroke={c} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round" fill="none"/></svg>;
  if (name === 'more') return <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><circle cx="11" cy="11" r="8" stroke={c} strokeWidth={sw} fill={fill}/><circle cx="7" cy="11" r="1" fill={c}/><circle cx="11" cy="11" r="1" fill={c}/><circle cx="15" cy="11" r="1" fill={c}/></svg>;
  return null;
}

// ── 상태바 (간단) ────────────────────────────────────
function FakeStatusBar({ dark = false }) {
  const c = dark ? '#fff' : 'var(--hg-ink)';
  return (
    <div style={{
      position: 'absolute', top: 0, left: 0, right: 0,
      height: 44, padding: '0 24px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      fontSize: 14, fontWeight: 700, color: c,
      zIndex: 10, pointerEvents: 'none',
    }}>
      <span>9:41</span>
      <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}>
        <svg width="16" height="11" viewBox="0 0 16 11" fill="none"><path d="M1 8h2v2H1zM5 6h2v4H5zM9 4h2v6H9zM13 2h2v8h-2z" fill={c}/></svg>
        <svg width="16" height="11" viewBox="0 0 16 11" fill="none"><path d="M8 2C4 2 2 5 1 6c1 1 3 4 7 4s6-3 7-4c-1-1-3-4-7-4z" stroke={c} strokeWidth="1.4" fill="none"/></svg>
        <svg width="22" height="11" viewBox="0 0 22 11" fill="none"><rect x="0.5" y="1" width="18" height="9" rx="2" stroke={c} strokeWidth="1" fill="none"/><rect x="2" y="2.5" width="14" height="6" rx="1" fill={c}/><rect x="19.5" y="4" width="1.5" height="3" rx="0.5" fill={c}/></svg>
      </span>
    </div>
  );
}

Object.assign(window, { IMG, ScreenHeader, Panel, Eyebrow, Chip, Checkbox, MoodImage, FAB, Sheet, PrimaryButton, BottomNav, NavIcon, FakeStatusBar, EmergencyFAB, BrandButton });

// ── 통합 컴포넌트 (인라인 정리용) ─────────────────────

// 전역 위급 호출 플로팅 버튼 — 탭바 위에 떠 있는
function EmergencyFAB({ onClick, mode = 'patient', hidden }) {
  if (hidden) return null;
  return (
    <button onClick={onClick} aria-label="병원 콜" style={{
      position: 'absolute',
      right: 18, bottom: 94,
      width: 54, height: 54, borderRadius: '50%',
      background: 'linear-gradient(135deg, var(--hg-rose), #A33E33)',
      color: '#fff',
      display: 'grid', placeItems: 'center',
      boxShadow: '0 8px 22px rgba(194,85,74,0.45), 0 2px 6px rgba(194,85,74,0.25)',
      zIndex: 90,
      transition: 'transform 160ms',
    }} onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.93)'} onMouseUp={(e) => e.currentTarget.style.transform = 'scale(1)'} onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}>
      <svg width="22" height="22" viewBox="0 0 22 22" fill="#fff">
        <path d="M5.5 3l3-1 2 3.8-2 2c1 3 3 5 6 6l2-2 3.8 2-1 3c-5 0-13.8-8.8-13.8-13.8z"/>
      </svg>
    </button>
  );
}

// 강조 CTA 버튼 — 더 선명한 그라데이션 + 큰 그림자
function BrandButton({ children, onClick, color = 'sage', icon, fullWidth = true, disabled }) {
  const palettes = {
    sage:  { from: '#A3BC92', to: '#7A9268', shadow: 'rgba(143,166,126,0.40)' },
    clay:  { from: '#C58668', to: '#8B5641', shadow: 'rgba(181,117,90,0.40)' },
    honey: { from: '#E8BC82', to: '#C58952', shadow: 'rgba(217,166,108,0.40)' },
    mist:  { from: '#C2BDD3', to: '#928BA8', shadow: 'rgba(173,168,194,0.40)' },
    rose:  { from: '#D86A5C', to: '#A33E33', shadow: 'rgba(194,85,74,0.40)' },
  };
  const p = palettes[color] || palettes.sage;
  return (
    <button onClick={onClick} disabled={disabled} style={{
      width: fullWidth ? '100%' : 'auto',
      minHeight: 56,
      background: disabled ? 'var(--hg-line)' : `linear-gradient(135deg, ${p.from}, ${p.to})`,
      color: '#fff',
      fontSize: 15, fontWeight: 700, letterSpacing: '-0.02em',
      borderRadius: 18,
      padding: '14px 22px',
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      boxShadow: disabled ? 'none' : `0 10px 24px ${p.shadow}, 0 2px 4px ${p.shadow}`,
      opacity: disabled ? 0.5 : 1,
      transition: 'transform 160ms, box-shadow 160ms',
    }}>
      {icon}
      {children}
    </button>
  );
}
