/* ============================================================
   Атрибьют — React-компоненты дизайн-системы v1.0
   Подключение: <script type="text/babel" src="components.jsx">
   Требует: design-system.css, React 18, icons.jsx
   ============================================================ */

const { useState, useEffect, useRef, createContext, useContext } = React;

// ── Brand context ──
const BrandContext = createContext('main');
const useBrand = () => useContext(BrandContext);

function BrandProvider({ defaultBrand = 'main', children }) {
  const [brand, setBrand] = useState(defaultBrand);
  useEffect(() => {
    document.documentElement.setAttribute('data-brand', brand);
  }, [brand]);
  return (
    <BrandContext.Provider value={{ brand, setBrand }}>
      {children}
    </BrandContext.Provider>
  );
}

// ── BrandSwitcher ──
function BrandSwitcher({ value, onChange }) {
  const brands = [
    { id: 'main', label: 'MED', color: '#EB5E57' },
    { id: 'kids', label: 'KIDS', color: '#F39EC5' },
    { id: 'dental', label: 'DENTAL', color: '#4E949E' },
  ];
  return (
    <div style={{ display: 'inline-flex', gap: 6, background: 'var(--color-neutral-100)',
      padding: 4, borderRadius: 'var(--r-full)' }}>
      {brands.map(b => (
        <button key={b.id} onClick={() => onChange(b.id)}
          style={{ border: 'none', background: value === b.id ? 'var(--color-brand-navy)' : 'transparent',
            color: value === b.id ? '#fff' : 'var(--color-neutral-700)',
            fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 700,
            letterSpacing: '.04em', padding: '7px 16px', borderRadius: 'var(--r-full)',
            cursor: 'pointer', transition: 'all .15s' }}>
          {b.label}
        </button>
      ))}
    </div>
  );
}

// ── Button ──
function Button({ variant = 'primary', size, block, disabled, icon, children, ...props }) {
  const cls = ['btn',
    variant === 'primary' && 'btn-primary',
    variant === 'secondary' && 'btn-secondary',
    variant === 'ghost' && 'btn-ghost',
    variant === 'icon' && 'btn-icon',
    size === 'lg' && 'btn-lg',
    block && 'btn-block',
  ].filter(Boolean).join(' ');
  return <button className={cls} disabled={disabled} {...props}>{children}</button>;
}

// ── Card ──
function Card({ hero, large, children, style, ...props }) {
  const cls = ['card', large && 'card-lg', hero && 'card-hero'].filter(Boolean).join(' ');
  return <div className={cls} style={style} {...props}>{children}</div>;
}

// ── Tag ──
function Tag({ variant, children, ...props }) {
  const cls = ['tag', variant && `tag-${variant}`].filter(Boolean).join(' ');
  return <span className={cls} {...props}>{children}</span>;
}

// ── Input ──
function Input({ label, hint, error, ...props }) {
  return (
    <div>
      {label && <label className="field-label">{label}</label>}
      <input className={`input${error ? ' input-error' : ''}`} {...props} />
      {hint && <div className={`field-hint${error ? ' error' : ''}`}>{hint}</div>}
    </div>
  );
}

// ── Chip ──
function Chip({ selected, disabled, children, ...props }) {
  const cls = ['chip', selected && 'selected', disabled && 'disabled'].filter(Boolean).join(' ');
  return <button className={cls} disabled={disabled} {...props}>{children}</button>;
}

// ── Avatar ──
function Avatar({ size = 44, brand = 'main', initials = 'А', src, photo }) {
  const img = photo || src;
  const bgClass = `avatar-${brand}`;
  return (
    <div className={`avatar ${bgClass}`}
      style={{ width: size, height: size, fontSize: size * 0.36,
        backgroundImage: img ? `url(${img})` : undefined,
        backgroundSize: img ? 'cover' : undefined,
        backgroundPosition: img ? 'center top' : undefined }}>
      {!img && initials}
    </div>
  );
}

// ── BrandPill ──
function BrandPill({ brand = 'main' }) {
  const names = { main: 'MED', kids: 'KIDS', dental: 'DENTAL' };
  return (
    <span className="brand-pill" data-brand={brand}>
      <span className="dot" />
      <span>{names[brand]}</span>
    </span>
  );
}

// ── Divider ──
function Divider({ style }) {
  return <div className="divider" style={{ margin: '12px 0', ...style }} />;
}

// ── Toast ──
function Toast({ children }) {
  return <div className="toast">{children}</div>;
}

// ── AppBar ──
function AppBar({ title, onBack, right, transparent = false }) {
  return (
    <div className="appbar" style={transparent ? { background: 'transparent' } : null}>
      <div className="row" style={{ gap: 12, flex: 1, minWidth: 0 }}>
        {onBack && (
          <button className="appbar-back" onClick={onBack} aria-label="Назад">
            {Icon.chevL({ size: 18, sw: 2.2 })}
          </button>
        )}
        <div className="appbar-title" style={{ overflow: 'hidden', textOverflow: 'ellipsis',
          whiteSpace: 'nowrap' }}>{title}</div>
      </div>
      {right}
    </div>
  );
}

// ── BottomNav ──
function BottomNav({ current = 'home', onNav }) {
  const items = [
    { id: 'home',    label: 'Главная',    icon: 'home' },
    { id: 'booking', label: 'Запись',     icon: 'calendar' },
    { id: 'records', label: 'Медкарта',   icon: 'clipboard' },
    { id: 'chat',    label: 'Поддержка',  icon: 'chat' },
    { id: 'profile', label: 'Профиль',    icon: 'user' },
  ];
  return (
    <div className="bnav">
      {items.map(it => {
        const active = current === it.id;
        const iconFn = Icon[it.icon];
        return (
          <button key={it.id} className={`bnav-item ${active ? 'active' : ''}`}
            onClick={() => onNav?.(it.id)}>
            {iconFn({ size: 22, sw: active ? 2 : 1.7 })}
            <span>{it.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// ── DoctorRow ──
function DoctorRow({ doctor, onClick, compact = false }) {
  const initials = doctor.name.split(' ').map(p => p[0]).join('').slice(0, 2);
  const bgByBrand = { main: '#FBE2E0', kids: '#FCE7F0', dental: '#D9EAEC' };
  return (
    <button onClick={onClick} style={{
      background: '#fff', border: 'none', borderRadius: 14,
      padding: compact ? 12 : 14, width: '100%', textAlign: 'left',
      boxShadow: 'var(--shadow-sm)', display: 'flex', gap: 12,
      alignItems: 'flex-start', cursor: 'pointer', fontFamily: 'inherit',
    }}>
      <div className="avatar" style={{
        width: compact ? 44 : 52, height: compact ? 44 : 52,
        background: bgByBrand[doctor.brand] || '#EEF0F4',
        fontSize: (compact ? 44 : 52) * 0.32,
      }}>{initials}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--color-neutral-900)',
          letterSpacing: '-0.01em', marginBottom: 2 }}>{doctor.name}</div>
        <div style={{ fontSize: 12, color: 'var(--color-neutral-400)', marginBottom: 6 }}>
          {doctor.title || doctor.specName}
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', fontSize: 11,
          color: 'var(--color-neutral-700)' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 2,
            color: 'var(--color-neutral-900)', fontWeight: 700 }}>
            ★ {doctor.rating}
          </span>
          <span className="muted">·</span>
          <span>{doctor.reviews} отзывов</span>
          <span className="muted">·</span>
          <span>{doctor.exp} лет</span>
        </div>
      </div>
      <div style={{ textAlign: 'right', flexShrink: 0 }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--color-accent)',
          whiteSpace: 'nowrap' }}>{doctor.next}</div>
        <div style={{ fontSize: 11, color: 'var(--color-neutral-400)', marginTop: 2 }}>
          от {doctor.price?.toLocaleString('ru')} ₽
        </div>
      </div>
    </button>
  );
}

// ── ServiceTile ──
function ServiceTile({ icon, name, desc, onClick }) {
  const iconFn = Icon[icon] || Icon.doc;
  return (
    <button onClick={onClick} style={{
      background: '#fff', border: 'none', borderRadius: 14, padding: 14,
      width: '100%', textAlign: 'left', boxShadow: 'var(--shadow-sm)',
      cursor: 'pointer', fontFamily: 'inherit',
    }}>
      <div style={{ width: 40, height: 40, borderRadius: 10, display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        background: 'color-mix(in srgb, var(--color-accent) 12%, transparent)',
        color: 'var(--color-accent)', marginBottom: 10 }}>
        {iconFn({ size: 20 })}
      </div>
      <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--color-neutral-900)',
        marginBottom: 2 }}>{name}</div>
      <div style={{ fontSize: 12, color: 'var(--color-neutral-400)' }}>{desc}</div>
    </button>
  );
}

// ── AppointmentCard (hero) ──
function AppointmentCard({ doctor, time, type, clinic }) {
  return (
    <Card hero>
      <div style={{ position: 'absolute', top: -40, right: -30, width: 160, height: 160,
        borderRadius: '50%', background: 'color-mix(in srgb, var(--color-accent) 28%, transparent)',
        opacity: .55 }} />
      <div style={{ position: 'relative' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          marginBottom: 14 }}>
          <Tag>Ближайший приём</Tag>
          <span style={{ fontSize: 11, opacity: .85, display: 'inline-flex', alignItems: 'center',
            gap: 5 }}>
            <span className="pulse" style={{ width: 6, height: 6, borderRadius: '50%',
              background: 'var(--color-accent)' }} />
            через 2 часа
          </span>
        </div>
        <div style={{ display: 'flex', gap: 14, alignItems: 'center', marginBottom: 16 }}>
          <Avatar size={60} brand="main" initials="ОЕ" />
          <div>
            <div style={{ fontFamily: 'var(--font-heading)', fontSize: 19, lineHeight: 1.15,
              letterSpacing: '-0.01em', marginBottom: 4 }}>{doctor}</div>
            <div style={{ fontSize: 12, opacity: .78 }}>{type} · {clinic}</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, fontSize: 12 }}>
          <span style={{ padding: '7px 10px', borderRadius: 8,
            background: 'rgba(255,255,255,.12)' }}>{time}</span>
          <span style={{ padding: '7px 10px', borderRadius: 8,
            background: 'rgba(255,255,255,.12)' }}>{type}</span>
        </div>
      </div>
    </Card>
  );
}

// ── Section header ──
function SectionHeader({ title, action, actionLabel }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
      padding: '18px 16px 8px' }}>
      <h2 className="h3" style={{ margin: 0 }}>{title}</h2>
      {action && (
        <button onClick={action} style={{ background: 'none', border: 'none',
          color: 'var(--color-accent)', fontSize: 12, fontWeight: 700,
          letterSpacing: '0.04em', textTransform: 'uppercase', cursor: 'pointer',
          fontFamily: 'var(--font-body)' }}>
          {actionLabel || 'Все'}
        </button>
      )}
    </div>
  );
}

// ── Phone screen wrapper ──
function PhoneScreen({ children, style }) {
  return (
    <div className="phone-screen" style={style}>
      <div className="phone-body">{children}</div>
      <BottomNav />
    </div>
  );
}

// Export all to window
Object.assign(window, {
  BrandProvider, BrandContext, useBrand,
  BrandSwitcher, Button, Card, Tag, Input, Chip, Avatar, BrandPill,
  Divider, Toast, AppBar, BottomNav, DoctorRow, ServiceTile,
  AppointmentCard, SectionHeader, PhoneScreen,
});
