// ============================================================
// COMPONENTS — Convés design system primitives
// ============================================================
const { useState, useEffect, useRef, useMemo } = React;

// ---------- Icon ----------
// Wraps lucide icons. Pass name as PascalCase (e.g. "Wrench")
function Icon({ name, size = 20, strokeWidth = 1.75, color = 'currentColor', style = {} }) {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current || !window.lucide) return;
    ref.current.innerHTML = '';
    const node = document.createElement('i');
    node.setAttribute('data-lucide', kebab(name));
    node.style.width = size + 'px';
    node.style.height = size + 'px';
    ref.current.appendChild(node);
    try { window.lucide.createIcons({ attrs: { 'stroke-width': strokeWidth, width: size, height: size, color }, nameAttr: 'data-lucide' }); } catch(e){}
  }, [name, size, strokeWidth, color]);
  return <span ref={ref} style={{ display:'inline-flex', alignItems:'center', justifyContent:'center', width:size, height:size, color, ...style }} />;
}
function kebab(s){ return s.replace(/([a-z0-9])([A-Z])/g,'$1-$2').toLowerCase(); }

// ---------- Currency / format helpers ----------
const brl = (n) => 'R$ ' + n.toLocaleString('pt-BR', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
const brlFull = (n) => 'R$ ' + n.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

// ---------- Button ----------
function Btn({ children, variant = 'primary', size = 'md', icon, iconRight, full, onClick, disabled, style={} }) {
  const base = {
    display:'inline-flex', alignItems:'center', justifyContent:'center', gap:8,
    border:'1px solid transparent', cursor: disabled ? 'not-allowed':'pointer',
    fontWeight:600, letterSpacing:-0.1, transition:'all .15s ease',
    whiteSpace:'nowrap', opacity: disabled ? .55 : 1,
  };
  const sizes = {
    sm: { fontSize:13, padding:'8px 12px', borderRadius:8 },
    md: { fontSize:15, padding:'12px 18px', borderRadius:12 },
    lg: { fontSize:16, padding:'14px 22px', borderRadius:12 },
  };
  const variants = {
    primary:    { background:'var(--primary)', color:'#fff' },
    secondary:  { background:'var(--surface)', color:'var(--text)', borderColor:'var(--border-strong)' },
    ghost:      { background:'transparent', color:'var(--text)' },
    accent:     { background:'var(--accent)', color:'#3A2D14' },
    danger:     { background:'var(--surface)', color:'var(--danger)', borderColor:'var(--border-strong)' },
    dark:       { background:'#131722', color:'#fff' },
  };
  return (
    <button className="ripple" onClick={disabled?undefined:onClick} disabled={disabled}
      style={{ ...base, ...sizes[size], ...variants[variant], width: full?'100%':undefined, ...style }}>
      {icon && <Icon name={icon} size={size==='sm'?14:18} strokeWidth={2} />}
      <span>{children}</span>
      {iconRight && <Icon name={iconRight} size={size==='sm'?14:18} strokeWidth={2} />}
    </button>
  );
}

// ---------- Trust Score Badge ----------
function TrustScoreBadge({ score, count, size='md', delta }) {
  const big = size === 'lg';
  return (
    <div style={{
      display:'inline-flex', alignItems:'center', gap:6,
      background:'var(--accent-soft)',
      border:'1px solid #E9DDC2',
      borderRadius: 999, padding: big ? '6px 12px':'4px 10px',
      color:'#3A2D14',
    }}>
      <Icon name="Star" size={big?16:13} color="#B5946A" strokeWidth={2.2} style={{fill:'#C5A572'}} />
      <span className="mono" style={{ fontWeight:600, fontSize: big?15:13 }}>{score.toFixed(1)}</span>
      <span style={{ color:'#7D6A47', fontSize: big?13:12 }}>· {count}</span>
      {delta && (
        <span style={{ color:'var(--success)', fontSize: big?12:11, fontWeight:600, marginLeft:2 }}>{delta}</span>
      )}
    </div>
  );
}

// ---------- Category Chip ----------
function CategoryChip({ icon, label, active, onClick }) {
  return (
    <button onClick={onClick} className="ripple" style={{
      display:'inline-flex', alignItems:'center', gap:8,
      padding:'9px 14px', borderRadius:999,
      border:'1px solid ' + (active ? 'var(--primary)' : 'var(--border)'),
      background: active ? 'var(--primary)' : 'var(--surface)',
      color: active ? '#fff' : 'var(--text)',
      fontSize:14, fontWeight: active ? 600 : 500,
      cursor:'pointer', whiteSpace:'nowrap',
    }}>
      {icon && <Icon name={icon} size={15} strokeWidth={2} />}
      {label}
    </button>
  );
}

// ---------- Order status pill ----------
function OrderStatusPill({ status, size='sm' }) {
  const m = STATUS_META[status] || STATUS_META['orcamento'];
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', gap:6,
      background: m.bg, color: m.color,
      padding: size==='sm' ? '3px 9px':'5px 11px',
      borderRadius:999, fontSize: size==='sm' ? 12:13, fontWeight:600,
    }}>
      <span style={{ width:6, height:6, borderRadius:6, background: m.dot, display:'inline-block' }} />
      {m.label}
    </span>
  );
}

// ---------- Boat illustration placeholder ----------
function BoatPlaceholder({ width='100%', height=120, label, rounded=12 }) {
  return (
    <div className="boat-illo" style={{
      width, height, borderRadius: rounded, position:'relative', overflow:'hidden',
      display:'flex', alignItems:'center', justifyContent:'center',
    }}>
      {/* Stylized boat silhouette using simple geometric primitives only */}
      <svg width="62%" height="auto" viewBox="0 0 200 80" style={{opacity:.85}}>
        {/* hull */}
        <path d="M10 56 Q 100 78, 190 56 L 175 64 Q 100 86, 25 64 Z" fill="#1F3864" />
        {/* deck */}
        <rect x="42" y="42" width="116" height="14" rx="2" fill="#2A4A7F" />
        {/* cabin */}
        <rect x="78" y="28" width="62" height="16" rx="2" fill="#1F3864" />
        {/* windshield */}
        <rect x="84" y="32" width="50" height="6" rx="1" fill="#C5A572" opacity=".6" />
        {/* waterline */}
        <line x1="0" y1="68" x2="200" y2="68" stroke="#1F3864" strokeOpacity=".15" strokeWidth="1" strokeDasharray="3 4"/>
      </svg>
      {label && (
        <div className="mono" style={{
          position:'absolute', bottom:8, left:10,
          fontSize:10, color:'#6B7A91', letterSpacing:.4, textTransform:'uppercase',
        }}>{label}</div>
      )}
    </div>
  );
}

// ---------- Boat Card ----------
function BoatCard({ boat, onClick, highlight }) {
  return (
    <button onClick={onClick} className="ripple" style={{
      display:'flex', alignItems:'stretch', gap:14, width:'100%', textAlign:'left',
      background:'var(--surface)', border:'1px solid ' + (highlight ? 'var(--primary)' : 'var(--border)'),
      borderRadius:16, padding:12, cursor:'pointer',
    }}>
      <BoatPlaceholder width={110} height={84} rounded={10} />
      <div style={{flex:1, display:'flex', flexDirection:'column', justifyContent:'space-between', minWidth:0}}>
        <div>
          <div style={{display:'flex', alignItems:'center', gap:6}}>
            <h3 style={{margin:0, fontSize:16, fontWeight:700, color:'var(--text)'}}>{boat.name}</h3>
            <span style={{fontSize:11, color:'var(--text-subtle)'}}>· {boat.length} pés</span>
          </div>
          <div style={{fontSize:13, color:'var(--text-muted)', marginTop:2}}>{boat.model} · {boat.year}</div>
        </div>
        <div style={{display:'flex', alignItems:'center', gap:10, fontSize:12, color:'var(--text-subtle)'}}>
          <span style={{display:'inline-flex',alignItems:'center',gap:4}}><Icon name="Cog" size={12} strokeWidth={2}/> {boat.motor.split(' ').slice(0,2).join(' ')}</span>
          <span style={{display:'inline-flex',alignItems:'center',gap:4}}><Icon name="MapPin" size={12} strokeWidth={2}/> {boat.marina.split(',')[0]}</span>
        </div>
      </div>
    </button>
  );
}

// ---------- Pro Card ----------
function ProCard({ pro, onClick, dense, action }) {
  return (
    <button onClick={onClick} className="ripple" style={{
      display:'flex', alignItems:'flex-start', gap:12, width:'100%', textAlign:'left',
      background:'var(--surface)', border:'1px solid var(--border)',
      borderRadius:16, padding: dense ? 12 : 14, cursor:'pointer',
    }}>
      <Avatar tone={pro.avatarTone} name={pro.short} size={dense?40:48} />
      <div style={{flex:1, minWidth:0}}>
        <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:2}}>
          <h3 style={{margin:0, fontSize:15, fontWeight:600, color:'var(--text)'}}>{pro.short}</h3>
          <Icon name="BadgeCheck" size={14} color="#1F3864" strokeWidth={2.2}/>
        </div>
        <div style={{fontSize:13, color:'var(--text-muted)', marginBottom:6}}>{pro.specialty}</div>
        <div style={{display:'flex', alignItems:'center', gap:10, flexWrap:'wrap'}}>
          <TrustScoreBadge score={pro.trust} count={pro.reviewCount}/>
          <span style={{fontSize:12, color:'var(--text-subtle)', display:'inline-flex', alignItems:'center', gap:4}}>
            <Icon name="Navigation" size={11} strokeWidth={2}/> {pro.distanceKm} km
          </span>
        </div>
      </div>
      {action || (
        <div style={{textAlign:'right'}}>
          <div className="mono" style={{fontSize:11, color:'var(--text-subtle)'}}>a partir de</div>
          <div className="mono" style={{fontSize:15, fontWeight:600, color:'var(--text)'}}>{brl(pro.basePrice)}</div>
        </div>
      )}
    </button>
  );
}

// ---------- Avatar ----------
function Avatar({ tone='#1F3864', name='', size=44 }) {
  const initials = name.split(' ').filter(Boolean).slice(0,2).map(w=>w[0]).join('').toUpperCase();
  return (
    <div style={{
      width:size, height:size, borderRadius: size,
      background: tone, color:'#fff', flexShrink:0,
      display:'flex', alignItems:'center', justifyContent:'center',
      fontWeight:600, fontSize: Math.round(size*0.36), letterSpacing:-.2,
    }}>{initials}</div>
  );
}

// ---------- Escrow Progress ----------
function EscrowProgress({ step=1 }) {
  const steps = [
    { label:'Cobrança', icon:'CreditCard' },
    { label:'Retido', icon:'Lock' },
    { label:'Em execução', icon:'Wrench' },
    { label:'Liberado', icon:'CheckCircle2' },
  ];
  return (
    <div style={{
      background:'var(--surface)', border:'1px solid var(--border)',
      borderRadius:16, padding:'18px 16px 14px',
    }}>
      <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:14}}>
        <div style={{fontSize:13, fontWeight:600, color:'var(--text)'}}>Pagamento em escrow</div>
        <div className="mono" style={{fontSize:11, color:'var(--text-subtle)'}}>etapa {step}/4</div>
      </div>
      <div style={{display:'flex', alignItems:'flex-start', position:'relative'}}>
        {steps.map((s,i)=>{
          const done = i < step;
          const active = i === step-1;
          return (
            <div key={i} style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center', position:'relative'}}>
              {i>0 && (
                <div style={{
                  position:'absolute', top:14, right:'50%', width:'100%', height:2,
                  background: done ? 'var(--primary)' : 'var(--border)',
                }}/>
              )}
              <div style={{
                width:28, height:28, borderRadius:28, position:'relative', zIndex:1,
                display:'flex', alignItems:'center', justifyContent:'center',
                background: done ? 'var(--primary)' : 'var(--surface)',
                border: '1.5px solid ' + (done ? 'var(--primary)' : 'var(--border-strong)'),
                color: done ? '#fff' : 'var(--text-subtle)',
                boxShadow: active ? '0 0 0 4px rgba(31,56,100,0.10)' : 'none',
              }}>
                <Icon name={done?'Check':s.icon} size={13} strokeWidth={2.4} color={done?'#fff':'var(--text-subtle)'}/>
              </div>
              <div style={{
                marginTop:8, fontSize:11, textAlign:'center',
                color: done ? 'var(--text)' : 'var(--text-subtle)',
                fontWeight: active ? 600 : 500, lineHeight:1.2,
              }}>{s.label}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ---------- Quote Card ----------
function QuoteCard({ quote, pro, onView, onAccept, onChat }) {
  return (
    <div style={{
      background:'var(--surface)',
      border:'1px solid ' + (quote.highlight ? 'var(--accent)' : 'var(--border)'),
      borderRadius:16, padding:16,
      boxShadow: quote.highlight ? '0 0 0 4px rgba(197,165,114,0.12)' : 'none',
      position:'relative', overflow:'hidden',
    }}>
      {quote.curated && (
        <div style={{
          display:'inline-flex', alignItems:'center', gap:6, marginBottom:12,
          background:'var(--accent-soft)', border:'1px solid #E9DDC2',
          color:'#3A2D14', padding:'4px 10px', borderRadius:999,
          fontSize:11.5, fontWeight:600, letterSpacing:.1,
        }}>
          <Icon name="Sparkles" size={12} color="#B5946A" strokeWidth={2.2}/>
          Sugerido pela curadoria
        </div>
      )}
      <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:10}}>
        <Avatar tone={pro.avatarTone} name={pro.short} size={36}/>
        <div style={{flex:1, minWidth:0}}>
          <div style={{fontSize:14, fontWeight:600, color:'var(--text)'}}>{pro.short}</div>
          <div style={{fontSize:12, color:'var(--text-muted)'}}>{pro.specialty}</div>
        </div>
        <TrustScoreBadge score={pro.trust} count={pro.reviewCount}/>
      </div>
      <div style={{display:'flex', alignItems:'baseline', gap:10, marginBottom:6}}>
        <div className="mono" style={{fontSize:26, fontWeight:700, color:'var(--text)', letterSpacing:-.5}}>{brl(quote.price)}</div>
        <div style={{fontSize:13, color:'var(--text-muted)'}}>· prazo {quote.days} {quote.days===1?'dia':'dias'}</div>
      </div>
      <p style={{margin:'4px 0 14px', fontSize:13, lineHeight:1.5, color:'var(--text-muted)'}}>{quote.note}</p>
      <div style={{display:'flex', gap:8}}>
        <Btn variant="secondary" size="sm" onClick={onChat} icon="MessageSquare">Conversar</Btn>
        <Btn variant="primary" size="sm" onClick={onAccept} style={{flex:1}}>Aceitar cotação</Btn>
      </div>
    </div>
  );
}

// ---------- Logbook Entry ----------
const CATEGORY_ICON = {
  mecanica:'Wrench', eletrica:'Zap', eletronica:'Radar',
  casco:'Sparkles', limpeza:'Droplets', marinheiro:'Anchor',
};
const CATEGORY_LABEL = {
  mecanica:'Mecânica', eletrica:'Elétrica', eletronica:'Eletrônica',
  casco:'Casco', limpeza:'Limpeza', marinheiro:'Marinheiro',
};
function LogbookEntry({ entry, isLast }) {
  const d = new Date(entry.date + 'T12:00:00');
  const day = d.toLocaleDateString('pt-BR',{day:'2-digit'});
  const month = d.toLocaleDateString('pt-BR',{month:'short'}).replace('.','');
  return (
    <div style={{display:'flex', gap:14, position:'relative'}}>
      <div style={{display:'flex', flexDirection:'column', alignItems:'center', flexShrink:0, width:48}}>
        <div className="mono" style={{fontSize:11, color:'var(--text-subtle)', textTransform:'uppercase', letterSpacing:.5}}>{month}</div>
        <div style={{fontSize:18, fontWeight:700, color:'var(--text)', lineHeight:1}}>{day}</div>
        <div style={{flex:1, width:1, background:'var(--border)', marginTop:6, marginBottom:isLast?0:0}}/>
      </div>
      <div style={{flex:1, paddingBottom:24, minWidth:0}}>
        <div style={{
          background:'var(--surface)', border:'1px solid var(--border)',
          borderRadius:14, padding:14,
        }}>
          <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:8}}>
            <div style={{
              width:30, height:30, borderRadius:8, background:'var(--accent-soft)',
              border:'1px solid #E9DDC2', display:'flex', alignItems:'center', justifyContent:'center',
            }}>
              <Icon name={CATEGORY_ICON[entry.category]} size={15} color="#7D6A47" strokeWidth={2}/>
            </div>
            <span style={{fontSize:12, fontWeight:600, color:'var(--text-muted)'}}>{CATEGORY_LABEL[entry.category]}</span>
            {entry.verified && (
              <span style={{display:'inline-flex',alignItems:'center',gap:4, marginLeft:'auto', fontSize:11, color:'var(--success)', fontWeight:600}}>
                <Icon name="BadgeCheck" size={12} color="var(--success)" strokeWidth={2.2}/> Verificado
              </span>
            )}
          </div>
          <div style={{fontSize:14.5, fontWeight:600, color:'var(--text)', lineHeight:1.4, marginBottom:6}}>{entry.title}</div>
          <div style={{display:'flex', alignItems:'center', gap:10, fontSize:12, color:'var(--text-muted)', flexWrap:'wrap'}}>
            <span>{entry.pro}</span>
            <span style={{color:'var(--text-subtle)'}}>·</span>
            <span className="mono">{entry.hoursMarker}h motor</span>
            <span style={{color:'var(--text-subtle)'}}>·</span>
            <span className="mono">{brl(entry.amount)}</span>
            {entry.attachments>0 && (
              <>
                <span style={{color:'var(--text-subtle)'}}>·</span>
                <span style={{display:'inline-flex',alignItems:'center',gap:3}}>
                  <Icon name="Paperclip" size={11} strokeWidth={2}/>{entry.attachments}
                </span>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- ReviewStars (3 dimensions) ----------
function ReviewStars({ dimensions, onChange, readOnly }) {
  const labels = { pontualidade:'Pontualidade', tecnica:'Qualidade técnica', limpeza:'Limpeza pós-serviço' };
  return (
    <div style={{display:'flex', flexDirection:'column', gap:14}}>
      {Object.keys(labels).map(key=>(
        <div key={key} style={{display:'flex', alignItems:'center', justifyContent:'space-between', gap:12}}>
          <div style={{fontSize:14, color:'var(--text)', fontWeight:500}}>{labels[key]}</div>
          <div style={{display:'flex', gap:4}}>
            {[1,2,3,4,5].map(n=>{
              const filled = (dimensions[key]||0) >= n;
              return (
                <button key={n} disabled={readOnly} onClick={()=>onChange && onChange(key,n)} style={{
                  border:'none', background:'transparent', cursor: readOnly?'default':'pointer', padding:2,
                }}>
                  <Icon name="Star" size={24} color={filled ? '#C5A572' : '#D1D5DB'} strokeWidth={1.5}
                    style={{ fill: filled ? '#C5A572' : 'transparent' }} />
                </button>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
}

// ---------- Empty State ----------
function EmptyState({ icon='Anchor', title, description, action, onAction }) {
  return (
    <div style={{
      display:'flex', flexDirection:'column', alignItems:'center',
      textAlign:'center', padding:'40px 24px',
    }}>
      <div style={{
        width:64, height:64, borderRadius:16, background:'var(--accent-soft)',
        border:'1px solid #E9DDC2', display:'flex', alignItems:'center', justifyContent:'center',
        marginBottom:16,
      }}>
        <Icon name={icon} size={28} color="#7D6A47" strokeWidth={1.5}/>
      </div>
      <h3 style={{margin:'0 0 8px', fontSize:17, fontWeight:600, color:'var(--text)'}}>{title}</h3>
      <p style={{margin:'0 0 18px', fontSize:14, lineHeight:1.5, color:'var(--text-muted)', maxWidth:280}}>{description}</p>
      {action && <Btn variant="primary" onClick={onAction}>{action}</Btn>}
    </div>
  );
}

// ---------- Skeleton ----------
function Skel({ w='100%', h=14, r=6, style={} }) {
  return <div className="pulse-skel" style={{ width:w, height:h, borderRadius:r, background:'#E9EBEF', ...style }}/>;
}

// ---------- Section header ----------
function SectionHeader({ title, action, onAction }) {
  return (
    <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 4px', marginBottom:12}}>
      <h2 style={{margin:0, fontSize:14, fontWeight:600, color:'var(--text-muted)', textTransform:'uppercase', letterSpacing:.4}}>{title}</h2>
      {action && (
        <button onClick={onAction} style={{
          background:'none', border:'none', color:'var(--primary)',
          fontSize:13, fontWeight:600, cursor:'pointer', padding:0,
        }}>{action}</button>
      )}
    </div>
  );
}

// ---------- Banner (network error) ----------
function NetBanner({ onRetry, message='Sem conexão. Verificando novamente…' }) {
  return (
    <div style={{
      display:'flex', alignItems:'center', gap:10,
      background:'#FCEFE0', border:'1px solid #F2D6A8', color:'#7A4A0A',
      padding:'10px 14px', borderRadius:12, fontSize:13, margin:'0 16px 12px',
    }}>
      <Icon name="WifiOff" size={16} color="#7A4A0A" strokeWidth={2}/>
      <span style={{flex:1}}>{message}</span>
      <button onClick={onRetry} style={{
        background:'transparent', border:'none', color:'#7A4A0A',
        fontWeight:600, fontSize:13, cursor:'pointer', textDecoration:'underline',
      }}>Tentar novamente</button>
    </div>
  );
}

// ---------- Field ----------
function Field({ label, hint, error, children, optional }) {
  return (
    <div style={{display:'flex', flexDirection:'column', gap:6}}>
      <div style={{display:'flex', alignItems:'baseline', justifyContent:'space-between'}}>
        <label style={{fontSize:13, fontWeight:600, color:'var(--text)'}}>{label}</label>
        {optional && <span style={{fontSize:11, color:'var(--text-subtle)'}}>opcional</span>}
      </div>
      {children}
      {hint && !error && <div style={{fontSize:12, color:'var(--text-subtle)'}}>{hint}</div>}
      {error && (
        <div style={{display:'inline-flex', alignItems:'center', gap:5, fontSize:12, color:'var(--danger)'}}>
          <Icon name="AlertCircle" size={12} color="var(--danger)" strokeWidth={2.2}/>
          {error}
        </div>
      )}
    </div>
  );
}
function Input(props) {
  return <input {...props} style={{
    width:'100%', padding:'12px 14px', borderRadius:8,
    border:'1px solid var(--border-strong)', background:'var(--surface)',
    fontFamily:'inherit', fontSize:14, color:'var(--text)', outline:'none',
    ...props.style,
  }}/>;
}
function Textarea(props) {
  return <textarea {...props} style={{
    width:'100%', padding:'12px 14px', borderRadius:8,
    border:'1px solid var(--border-strong)', background:'var(--surface)',
    fontFamily:'inherit', fontSize:14, color:'var(--text)', outline:'none',
    resize:'vertical', minHeight:96,
    ...props.style,
  }}/>;
}

// ---------- ScreenHeader: title + optional back/right action ----------
function ScreenHeader({ title, subtitle, onBack, right, sticky=true, transparent=false, large=false }) {
  return (
    <div style={{
      position: sticky ? 'sticky' : 'relative', top:0, zIndex:10,
      background: transparent ? 'transparent' : 'rgba(250,250,250,0.92)',
      backdropFilter: transparent ? 'none' : 'saturate(160%) blur(10px)',
      WebkitBackdropFilter: transparent ? 'none' : 'saturate(160%) blur(10px)',
      borderBottom: transparent ? 'none' : '1px solid var(--border)',
      padding: large ? '14px 16px 6px' : '10px 12px',
    }}>
      <div style={{display:'flex', alignItems:'center', gap:8}}>
        {onBack && (
          <button onClick={onBack} className="ripple" style={{
            width:36, height:36, borderRadius:36, border:'none', background:'var(--surface)',
            display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer',
            border:'1px solid var(--border)',
          }}>
            <Icon name="ChevronLeft" size={20} strokeWidth={2}/>
          </button>
        )}
        <div style={{flex:1, minWidth:0, padding: onBack ? '0' : '0 6px'}}>
          <div style={{fontSize: large?22:16, fontWeight: large?700:600, color:'var(--text)', lineHeight:1.2}}>{title}</div>
          {subtitle && <div style={{fontSize:12, color:'var(--text-muted)', marginTop:2}}>{subtitle}</div>}
        </div>
        {right}
      </div>
    </div>
  );
}

// ---------- TabBar ----------
function TabBar({ active, onChange, items }) {
  return (
    <div style={{
      position:'absolute', bottom:0, left:0, right:0,
      paddingBottom: 30, paddingTop:8, paddingLeft:8, paddingRight:8,
      background:'rgba(255,255,255,0.94)',
      backdropFilter:'saturate(160%) blur(20px)',
      WebkitBackdropFilter:'saturate(160%) blur(20px)',
      borderTop:'1px solid var(--border)',
      display:'flex', justifyContent:'space-around', alignItems:'flex-end',
      zIndex: 30,
    }}>
      {items.map(item=>{
        const on = active === item.key;
        return (
          <button key={item.key} onClick={()=>onChange(item.key)} className="tab-pop" style={{
            background:'none', border:'none', cursor:'pointer',
            display:'flex', flexDirection:'column', alignItems:'center', gap:3,
            padding:'6px 6px 4px', color: on ? 'var(--primary)' : 'var(--text-subtle)',
            minWidth:56, position:'relative',
          }}>
            {item.badge && (
              <span style={{
                position:'absolute', top:0, right:8, minWidth:16, height:16, padding:'0 4px',
                borderRadius:16, background:'var(--danger)', color:'#fff',
                fontSize:10, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center',
              }}>{item.badge}</span>
            )}
            <Icon name={item.icon} size={22} strokeWidth={on ? 2.2 : 1.7} color={on ? 'var(--primary)' : 'var(--text-subtle)'} />
            <span style={{fontSize:10.5, fontWeight: on?600:500, letterSpacing:-.1}}>{item.label}</span>
          </button>
        );
      })}
    </div>
  );
}

Object.assign(window, {
  Icon, brl, brlFull, Btn, TrustScoreBadge, CategoryChip, OrderStatusPill,
  BoatPlaceholder, BoatCard, ProCard, Avatar, EscrowProgress, QuoteCard,
  LogbookEntry, CATEGORY_ICON, CATEGORY_LABEL, ReviewStars, EmptyState, Skel,
  SectionHeader, NetBanner, Field, Input, Textarea, ScreenHeader, TabBar,
});
