/* ===================== SwiftBill shared components ===================== */
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

/* ---------- Icons (stroke, 1.8) ---------- */
function Icon({ name, size = 18, className = '', style }) {
  const p = {
    dashboard: 'M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z',
    scope: 'M9 11l3 3L22 4 M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11',
    table: 'M3 3h18v18H3z M3 9h18 M3 15h18 M9 3v18',
    layers: 'M12 2 2 7l10 5 10-5-10-5z M2 17l10 5 10-5 M2 12l10 5 10-5',
    money: 'M12 1v22 M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6',
    search: 'M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z M21 21l-4.3-4.3',
    bell: 'M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9 M13.7 21a2 2 0 0 1-3.4 0',
    logout: 'M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4 M16 17l5-5-5-5 M21 12H9',
    plus: 'M12 5v14 M5 12h14',
    chevR: 'M9 18l6-6-6-6',
    chevD: 'M6 9l6 6 6-6',
    chevU: 'M18 15l-6-6-6 6',
    chevL: 'M15 18l-6-6 6-6',
    check: 'M20 6 9 17l-5-5',
    x: 'M18 6 6 18 M6 6l12 12',
    building: 'M3 21h18 M5 21V7l8-4v18 M19 21V11l-6-4 M9 9v.01 M9 12v.01 M9 15v.01 M9 18v.01',
    pin: 'M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z M12 10a3 3 0 1 0 0-1z',
    cal: 'M3 4h18v18H3z M16 2v4 M8 2v4 M3 10h18',
    trash: 'M3 6h18 M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6 M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2',
    clock: 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z M12 6v6l4 2',
    plusC: 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z M12 8v8 M8 12h8',
    zoomIn: 'M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z M21 21l-4.3-4.3 M11 8v6 M8 11h6',
    zoomOut: 'M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z M21 21l-4.3-4.3 M8 11h6',
    file: 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6',
    excel: 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M9 13l3 5 M12 13l-3 5',
    filter: 'M22 3H2l8 9.5V19l4 2v-8.5z',
    edit: 'M12 20h9 M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z',
    save: 'M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z M17 21v-8H7v8 M7 3v5h8',
    bookmark: 'M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z',
    sparkle: 'M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z',
    shield: 'M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z M9 12l2 2 4-4',
    pie: 'M21 12A9 9 0 1 1 12 3v9z M21 12a9 9 0 0 0-9-9v9z',
    info: 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z M12 16v-4 M12 8h.01',
    grid: 'M3 3h7v7H3z M14 3h7v7h-7z M14 14h7v7h-7z M3 14h7v7H3z',
    inbox: 'M22 12h-6l-2 3h-4l-2-3H2 M5.5 5.5 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.5-6.5A2 2 0 0 0 16.8 4H7.2a2 2 0 0 0-1.7 1.5z',
    arrowR: 'M5 12h14 M13 5l7 7-7 7',
    ruler: 'M21.3 8.7 8.7 21.3a1 1 0 0 1-1.4 0l-4.6-4.6a1 1 0 0 1 0-1.4L15.3 2.7a1 1 0 0 1 1.4 0l4.6 4.6a1 1 0 0 1 0 1.4z M7 17l1.5-1.5 M11 13l1.5-1.5 M15 9l1.5-1.5',
    panel: 'M3 3h18v18H3z M9 3v18',
    menu: 'M3 6h18 M3 12h18 M3 18h18',
    user: 'M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2 M12 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z',
    lock: 'M19 11H5a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7a2 2 0 0 0-2-2z M7 11V7a5 5 0 0 1 10 0v4',
    eye: 'M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z',
    eyeOff: 'M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 10 7 10 7a13.2 13.2 0 0 1-1.67 2.68 M6.61 6.61A13.5 13.5 0 0 0 2 12s3 7 10 7a9.12 9.12 0 0 0 3.9-.85 M14.12 14.12a3 3 0 1 1-4.24-4.24 M1 1l22 22',
    upload: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4 M17 8l-5-5-5 5 M12 3v12',
    download: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4 M7 10l5 5 5-5 M12 15V3',
    cloud: 'M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z M12 12v5 M9 14l3-2 3 2',
    refresh: 'M23 4v6h-6 M1 20v-6h6 M3.5 9a9 9 0 0 1 14.9-3.4L23 10 M1 14l4.6 4.4A9 9 0 0 0 20.5 15',
    bolt: 'M13 2 3 14h9l-1 8 10-12h-9z',
    droplet: 'M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z',
    leaf: 'M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10z M2 21c0-3 1.85-5.36 5.08-6',
    cog: 'M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z M19.4 13a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z',
    weight: 'M15 5a3 3 0 1 1-6 0 3 3 0 0 1 6 0 M6.5 8a2 2 0 0 0-1.905 1.46L2.1 18.5A2 2 0 0 0 4 21h16a2 2 0 0 0 1.925-2.54L19.4 9.5A2 2 0 0 0 17.48 8Z',
    home: 'M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z M9 22V12h6v10',
    chat: 'M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z',
    copy: 'M9 9h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2z M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1',
    star: 'M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14l-5-4.87 6.91-1.01z'
  }[name] || '';
  return (
    <svg className={'ic ' + className} style={style} width={size} height={size} viewBox="0 0 24 24"
    fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      {p.split(' M').map((seg, i) => <path key={i} d={(i ? 'M' : '') + seg} />)}
    </svg>);

}

/* ---------- Status badge ---------- */
function StatusBadge({ status }) {
  const s = STATUS[status];if (!s) return null;
  return <span className={'badge ' + s.cls}><span className="pin"></span>{s.th}</span>;
}

/* ---------- Toast system ---------- */
const ToastCtx = createContext(() => {});
function useToast() {return useContext(ToastCtx);}
function ToastHost({ children }) {
  const [list, setList] = useState([]);
  const push = (msg, icon = 'check') => {
    const id = Math.random().toString(36).slice(2);
    setList((l) => [...l, { id, msg, icon }]);
    setTimeout(() => setList((l) => l.filter((t) => t.id !== id)), 2200);
  };
  return (
    <ToastCtx.Provider value={push}>
      {children}
      <div className="toasts">
        {list.map((t) =>
        <div className="toast" key={t.id}>
            <Icon name={t.icon} size={16} className="tk" style={{ color: '#34d399' }} />{t.msg}
          </div>
        )}
      </div>
    </ToastCtx.Provider>);

}

/* ---------- Modal ---------- */
function Modal({ title, sub, children, onClose, foot, wide, xwide, full, icon }) {
  useEffect(() => {
    const h = (e) => {if (e.key === 'Escape') onClose();};
    window.addEventListener('keydown', h);return () => window.removeEventListener('keydown', h);
  }, []);
  return (
    <div className="scrim" onMouseDown={(e) => {if (e.target === e.currentTarget) onClose();}}>
      <div className={'modal scrollthin ' + (full ? 'full' : (xwide ? 'xwide' : (wide ? 'wide' : '')))}>
        <div className="modal-head">
          {icon && <div className="modal-icon"><Icon name={icon} size={20} /></div>}
          <div style={{flex:1,minWidth:0}}>
            <div className="mt">{title}</div>
            {sub && <div className="ms">{sub}</div>}
          </div>
          <button className="minibtn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="modal-body">{children}</div>
        {foot && <div className="modal-foot">{foot}</div>}
      </div>
    </div>);

}

/* ---------- Side modal (right drawer) ---------- */
function SideModal({ title, sub, children, onClose, foot }) {
  useEffect(() => {
    const h = (e) => {if (e.key === 'Escape') onClose();};
    window.addEventListener('keydown', h);return () => window.removeEventListener('keydown', h);
  }, []);
  return (
    <div className="side-scrim" onMouseDown={(e) => {if (e.target === e.currentTarget) onClose();}}>
      <div className="side-modal">
        <div className="side-modal-head">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
            <div>
              <div className="mt" style={{ fontSize: 17, fontWeight: 600 }}>{title}</div>
              {sub && <div className="ms" style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 3 }}>{sub}</div>}
            </div>
            <button className="minibtn" onClick={onClose}><Icon name="x" size={18} /></button>
          </div>
        </div>
        <div className="side-modal-body scrollthin">{children}</div>
        {foot && <div className="side-modal-foot">{foot}</div>}
      </div>
    </div>);

}

/* ---------- Sidebar ---------- */
// ขั้นตอนงาน (flow steps) — เลข + สี phase ต่อขั้น (ดีไซน์ v0)
const SB_FLOW = [
  { id:'upload',   step:1, ic:'upload',   label:'อัปโหลดแบบ',          s:'อัปโหลดแบบ',        hex:'#6366f1' },
  { id:'scope',    step:2, ic:'scope',    label:'ขอบเขต & ใบเสนอราคา', s:'เลือกขอบเขต',       hex:'#0891b2' },
  { id:'results',  step:3, ic:'table',    label:'ผลลัพธ์ปริมาณ',       s:'ผลลัพธ์ปริมาณงาน',  hex:'#d97706' },
  { id:'pricing',  step:4, ic:'money',    label:'จับคู่ราคา',          s:'ตรวจสอบราคา',       hex:'#9333ea' },
  { id:'delivery', step:5, ic:'download', label:'ดาวน์โหลด',          s:'ส่งออก',            hex:'#16a34a' },
];

// ถอดปริมาณแล้วย้อนไปอัปโหลด/เลือกขอบเขตไม่ได้ (1 เครดิต = 1 โปรเจกต์ · กันถอดซ้ำ) — ด่านจริงอยู่ที่ nav() ใน app.jsx
const SB_STEP_LOCKED = ['upload','scope'];
const SB_STEP_LOCK_MSG = 'ถอดปริมาณแล้ว ย้อนกลับไม่ได้';

function Sidebar({ screen, project, collapsed, onToggle, onNav, onExit, user, locked, isAdmin, credits, analyzed }) {
  const inProject = !!project;
  const launchBalloons = useBalloon();
  const prevCollapsed  = useRef(collapsed);
  useEffect(()=>{
    if(collapsed && !prevCollapsed.current) launchBalloons();
    prevCollapsed.current = collapsed;
  }, [collapsed]);

  // ดึงชื่อ/อักษรย่อจาก user จริง
  const displayName = user?.user_metadata?.full_name
    || user?.user_metadata?.name
    || (user?.email ? user.email.split('@')[0] : 'ผู้ใช้');
  const avatarLetter = displayName.charAt(0).toUpperCase();
  const userEmail = user?.email || '';

  if (collapsed) {
    const rail = (id, ic, label, disabled = false) => {
      const isLocked = locked;   // ระหว่าง AI ถอดปริมาณ ล็อกทุกเมนูรวมถึงแดชบอร์ด ป้องกันการขัดจังหวะ
      return (
        <button key={id}
          className={'rail-item ' + (screen === id ? 'active' : '') + (disabled || isLocked ? ' disabled' : '')}
          title={isLocked ? 'SwiftBill กำลังวิเคราะห์ กรุณารอ…' : label}
          onClick={() => !disabled && !isLocked && onNav(id)}>
          <Icon name={ic} size={20} />
        </button>
      );
    };

    // ขั้นตอนงานแบบย่อ — สีตาม phase เหมือนเมนูเต็ม (ไอคอน+แถบซ้ายสีขั้น · ขั้นที่ผ่านแล้วมี ✓ สีขั้นที่มุม)
    const curStep = (SB_FLOW.find(s=>s.id===screen)||{}).step || 0;
    const railStep = (s) => {
      const active = screen===s.id, done = curStep>0 && s.step<curStep;
      const label = s.id==='delivery' ? 'ดาวน์โหลด '+(project.pricing?'BOQ':'BOM') : s.label;
      const past = analyzed && SB_STEP_LOCKED.includes(s.id);
      return (
        <button key={s.id}
          className={'rail-item rail-step'+(active?' active':'')+(locked?' disabled':'')+(past?' step-past':'')}
          style={active?{boxShadow:'inset 3px 0 0 '+s.hex, color:s.hex}:undefined}
          title={locked ? 'SwiftBill กำลังวิเคราะห์ กรุณารอ…' : past ? SB_STEP_LOCK_MSG : s.step+'. '+label}
          onClick={() => !locked && !past && onNav(s.id)}>
          <Icon name={s.ic} size={20} />
          {done && <span className="rail-step-done" style={{background:s.hex}}><Icon name="check" size={9}/></span>}
        </button>
      );
    };

    return (
      <aside className="side collapsed">
        <button className="rail-logo" title="ขยายเมนู" onClick={onToggle}>
          <div className="side-logo"><img src="assets/favicon-mark.svg?v=1" alt="SwiftBill"/></div>
        </button>
        {rail('dashboard', 'home', 'หน้าหลัก')}
        {isAdmin && rail('admin', 'shield', 'ผู้ดูแลระบบ')}
        {inProject && <>
          <div className="rail-div"></div>
          {SB_FLOW.map(railStep)}
        </>}
        <div className="side-spacer"></div>
        {rail('templates', 'bookmark', 'เทมเพลตราคาของฉัน')}
        {rail('steel', 'ruler', 'ตารางน้ำหนักเหล็ก')}
        {rail('feedback', 'chat', 'ส่ง Feedback')}
        <div className="rail-div"></div>
        <div className="avatar" title={displayName + ' · ' + userEmail}>{avatarLetter}</div>
        <button className="rail-item" title="ออกจากระบบ"
          style={{color:'var(--ink-3)'}}
          onClick={() => onNav('logout')}>
          <Icon name="logout" size={20} />
        </button>
      </aside>);
  }

  const item = (id, ic, label, sub = false, disabled = false) => {
    const isLocked = locked;   // ระหว่าง AI ถอดปริมาณ ล็อกทุกเมนูรวมถึงแดชบอร์ด ป้องกันการขัดจังหวะ
    return (
      <button className={'nav-item ' + (sub ? 'sub ' : '') + (screen === id ? 'active' : '') + (disabled || isLocked ? ' disabled' : '')}
        title={isLocked ? 'SwiftBill กำลังวิเคราะห์อยู่ กรุณารอจนเสร็จ' : undefined}
        onClick={() => !disabled && !isLocked && onNav(id)}>
        {!sub && <Icon name={ic} size={18} />}
        {sub && <span style={{ width: 6, height: 6, borderRadius: 3, background: 'currentColor', opacity: .5, marginLeft: 6 }}></span>}
        <span style={{ flex: 1, textAlign: 'left' }}>{label}</span>
        {isLocked && sub && <span className="spin" style={{width:10,height:10,flex:'0 0 10px'}}></span>}
      </button>
    );
  };

  // ── ขั้นตอนงาน (flow steps) — ดีไซน์ v0: เลข + สี phase + ✓ เมื่อเสร็จ ──
  const curStep = (SB_FLOW.find(s=>s.id===screen)||{}).step || 0;
  const flowStep = (s) => {
    const active = screen===s.id, done = curStep>0 && s.step<curStep, on = active||done;
    const label = s.id==='delivery' ? 'ดาวน์โหลด '+(project.pricing?'BOQ':'BOM') : s.label;
    const past = analyzed && SB_STEP_LOCKED.includes(s.id);
    return (
      <button key={s.id}
        className={'side-step'+(active?' active':'')+(done?' done':'')+(locked?' disabled':'')+(past?' step-past':'')}
        style={active?{boxShadow:'inset 3px 0 0 '+s.hex}:undefined}
        title={locked?'SwiftBill กำลังวิเคราะห์อยู่ กรุณารอ':past?SB_STEP_LOCK_MSG:undefined}
        onClick={()=>!locked && !past && onNav(s.id)}>
        <span className="side-step-badge" style={on?{background:s.hex,color:'#fff'}:undefined}>
          {done ? <Icon name="check" size={13}/> : s.step}
        </span>
        <Icon name={s.ic} size={17} style={active?{color:s.hex}:undefined}/>
        <span className="side-step-nm">{label}</span>
        {active && <Icon name="chevR" size={15} className="side-step-chev"/>}
        {locked && <span className="spin" style={{width:10,height:10,flex:'0 0 10px'}}></span>}
      </button>
    );
  };

  return (
    <aside className="side">
      <div className="side-brand">
        <div className="side-logo"><img src="assets/favicon-mark.svg?v=1" alt="SwiftBill"/></div>
        <div className="side-name">SwiftBill</div>
      </div>

      {item('dashboard', 'home', 'หน้าหลัก')}
      {isAdmin && item('admin', 'shield', 'ผู้ดูแลระบบ')}

      {inProject && <>
        <div className="side-sec">ขั้นตอนงาน</div>
        {SB_FLOW.map(flowStep)}
      </>}

      <div className="side-spacer"><CatRunner/></div>
      <div className="side-sec">เครื่องมือ</div>
      {item('templates', 'bookmark', 'เทมเพลตราคาของฉัน')}
      {item('steel', 'ruler', 'ตารางน้ำหนักเหล็ก')}
      {item('feedback', 'chat', 'ส่ง Feedback')}

      <div className="side-foot">
        {credits != null && !isAdmin && (
          <div className="side-credits" title="เครดิตคงเหลือ (จำนวนโปรเจกต์ที่สร้างได้)">
            <Icon name="star" size={14}/> <b>{credits}</b> เครดิต
          </div>
        )}
        <div className="side-user">
          <div className="avatar">{avatarLetter}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="nm">{displayName}</div>
            <div className="rl" style={{overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{userEmail}</div>
          </div>
          <button className="minibtn" style={{ color: '#c0cbdd' }}
            title="ออกจากระบบ"
            onClick={() => onNav('logout')}><Icon name="logout" size={17} /></button>
        </div>
      </div>
    </aside>);
}

/* ---------- Topbar ----------
   ตอนเปิดโปรเจค (อยู่ใน flow): ซ้าย = 🏠 หน้าหลัก › [ขั้นที่ N] ชื่อขั้น · ขวา = pill ชื่อโปรเจค + เครดิต
   หน้าอื่น (dashboard ฯลฯ): ขวา = เครดิตอย่างเดียว (เอาช่องค้นหา/กระดิ่ง/โปรไฟล์ที่ไม่ได้ทำงานจริงออก 2026-11-15) */
const SB_TOPBAR_HOLD_MS = 10000;
function Topbar({ screen, project, onNav, onToggleSidebar, user, credits }) {
  const flow = SB_FLOW.find(s => s.id === screen);
  const inFlow = !!(flow && project);
  // แถบบนซ่อนเองในขั้นตอนงาน: เข้าหน้าโชว์ค้าง 10 วิ แล้วเลื่อนขึ้นพร้อมเนื้อหาด้านล่าง (คืนพื้นที่จริง) · เอาเม้าท์ไปขอบบนเพื่อเรียกกลับ
  // ‼️ จอสัมผัสไม่มี hover = ซ่อนแล้วเรียกกลับไม่ได้ → คงแถบไว้
  const autoHide = inFlow && window.matchMedia('(hover: hover)').matches;
  const [shown, setShown] = useState(true);
  const hideTimer = useRef(null);
  const holdUntil = useRef(0);   // เม้าท์ผ่านแถบช่วง 10 วิแรกไม่ทำให้ซ่อนเร็วขึ้น
  const reveal = () => { clearTimeout(hideTimer.current); setShown(true); };
  const conceal = () => {
    clearTimeout(hideTimer.current);
    hideTimer.current = setTimeout(()=>setShown(false), Math.max(350, holdUntil.current-Date.now()));
  };
  useEffect(()=>{
    if(!autoHide) return;
    holdUntil.current = Date.now()+SB_TOPBAR_HOLD_MS;
    setShown(true);
    conceal();
    return ()=>clearTimeout(hideTimer.current);
  }, [autoHide, screen, project?.id]);
  return (<>
    {autoHide && <div className="topbar-hot" onMouseEnter={reveal} onMouseLeave={conceal}/>}
    <header className={'topbar'+(autoHide?' auto':'')+(autoHide&&shown?' shown':'')}
      onMouseEnter={autoHide?reveal:undefined} onMouseLeave={autoHide?conceal:undefined}
      onFocus={autoHide?reveal:undefined} onBlur={autoHide?conceal:undefined}>
      {onToggleSidebar && <button className="nav-toggle" title="ยุบ/ขยายเมนู" onClick={onToggleSidebar}><Icon name="menu" size={18} /></button>}
      {inFlow && (
        <div className="crumb-nav">
          <button className="crumb-home" onClick={() => onNav && onNav('dashboard')}>
            <Icon name="home" size={16} /> หน้าหลัก
          </button>
          <Icon name="chevR" size={15} className="crumb-sep" />
          <span className="crumb-step" style={{ background: flow.hex }}>ขั้นที่ {flow.step}</span>
          <span className="crumb-step-nm">{flow.s}</span>
        </div>
      )}
      <div className="top-actions">
        {inFlow && (
          <div className="proj-pill" title={project.name}>
            <Icon name="building" size={15} /> <span className="proj-lb">โครงการ:</span> <b>{project.name}</b>
          </div>
        )}
        {credits != null && (
          <button className="credit-chip" title="เครดิตคงเหลือ — คลิกเพื่อเติมเครดิต" onClick={()=>onNav && onNav('topup')}>
            <Icon name="star" size={14}/> <b>{credits}</b> เครดิต <span className="cc-plus"><Icon name="plus" size={12}/></span>
          </button>
        )}
      </div>
    </header>
  </>);
}

/* ---------- Feedback modal → ตาราง feedback ใน Supabase (admin อ่านที่หน้าผู้ดูแลระบบ) ---------- */
const FB_TYPES = [
  { id:'review', th:'รีวิว',        ic:'star' },   // ต้องมีดาว + ข้อความ ≥ 10 ตัว (DB บังคับด้วย · migration 0012)
  { id:'bug',    th:'บั๊ก/ปัญหา',  ic:'info' },
  { id:'idea',   th:'ข้อเสนอแนะ',  ic:'sparkle' },
  { id:'praise', th:'ชมเชย',       ic:'check' },
  { id:'other',  th:'อื่นๆ',        ic:'chat' },
];
// gate = รีวิวก่อนดาวน์โหลดไฟล์ครั้งแรก (ผู้ใช้เครดิตทดลอง · หน้าส่งออก) → ซ่อนตัวเลือกประเภท · ส่งสำเร็จเรียก onSent (ดาวน์โหลดต่อ)
//   initialType = เปิดมาที่ประเภทนั้น (ปุ่ม "เขียนรีวิว")
const SB_REVIEW_MIN = 10;
function FeedbackModal({ user, screen, project, onClose, initialType, gate, onSent }){
  const toast = useToast();
  const [type,setType]       = useState(gate ? 'review' : (initialType || 'bug'));
  const [rating,setRating]   = useState(0);
  const [hover,setHover]     = useState(0);
  const [message,setMessage] = useState('');
  const [status,setStatus]   = useState('idle');   // 'idle'|'sending'|'sent'|'error'

  const isReview = type === 'review';
  const canSend = !!message.trim() && status!=='sending' && (!isReview || (rating > 0 && message.trim().length >= SB_REVIEW_MIN));
  const send = async () => {
    if(!canSend) return;
    if(!user){ setStatus('error'); return; }
    setStatus('sending');
    const real = project && !project.__demo;   // โปรเจกต์สาธิตไม่มี id จริงใน DB
    const { error } = await window.submitFeedback({
      user_id: user.id, user_email: user.email || null,
      type, rating: rating || null, message: message.trim(),
      screen: screen || null,
      project_id: real ? project.id : null, project_name: project ? (project.name || null) : null,
    });
    if(error){ console.warn('feedback send failed:', error); setStatus('error'); return; }
    setStatus('sent');
    if(isReview && onSent) onSent();   // รีวิวสำเร็จ (บังคับหรือเขียนเอง) → หน้าส่งออกเลิกถาม · gate = ดาวน์โหลดต่อ
    if(gate){ toast('ขอบคุณสำหรับรีวิว ✓','check'); onClose(); return; }
    toast(isReview ? 'ขอบคุณสำหรับรีวิว ✓' : 'ขอบคุณสำหรับ feedback ✓','check');
    setTimeout(onClose, 1000);
  };
  const title = gate ? 'รีวิวการใช้งาน SwiftBill' : (isReview ? 'เขียนรีวิว' : 'ส่ง Feedback');

  if(status==='sent'){
    return (
      <Modal title={title} icon="chat" onClose={onClose}>
        <div style={{textAlign:'center',padding:'22px 10px'}}>
          <div style={{width:56,height:56,borderRadius:'50%',background:'var(--green-soft)',color:'var(--green)',
            display:'flex',alignItems:'center',justifyContent:'center',margin:'0 auto 14px'}}><Icon name="check" size={28}/></div>
          <div style={{fontSize:16,fontWeight:700}}>ส่งเรียบร้อย ขอบคุณมากครับ 🙏</div>
        </div>
      </Modal>
    );
  }
  return (
    <Modal title={title} icon={isReview ? 'star' : 'chat'}
      sub={gate ? 'ก่อนดาวน์โหลดไฟล์ครั้งแรก กรุณาให้คะแนนและความเห็นต่อการใช้งานเครดิตทดลอง ท่านให้คะแนนตามจริงได้ทุกระดับ' : 'ความเห็นของคุณช่วยให้ SwiftBill ดีขึ้น'}
      onClose={onClose}
      foot={<>
        <button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button>
        <button className="btn btn-primary" disabled={!canSend} onClick={send}>
          {status==='sending'
            ? <><span className="spin" style={{width:14,height:14}}></span> กำลังส่ง…</>
            : gate ? <><Icon name="excel" size={15}/> ส่งรีวิวและดาวน์โหลด</>
            : <><Icon name="upload" size={15}/> {isReview ? 'ส่งรีวิว' : 'ส่ง Feedback'}</>}
        </button>
      </>}>
      {!gate && <div className="field" style={{marginBottom:16}}>
        <label>ประเภท</label>
        <div className="fb-types">
          {FB_TYPES.map(t=>(
            <button key={t.id} className={'fb-type'+(type===t.id?' on':'')} onClick={()=>setType(t.id)}>
              <Icon name={t.ic} size={15}/> {t.th}
            </button>
          ))}
        </div>
      </div>}
      <div className="field" style={{marginBottom:16}}>
        <label>ให้คะแนน <span className="hintl">{isReview ? '(จำเป็น)' : '(ไม่บังคับ)'}</span></label>
        <div className="fb-stars" onMouseLeave={()=>setHover(0)}>
          {[1,2,3,4,5].map(n=>(
            <button key={n} className={'fb-star'+((hover||rating)>=n?' on':'')}
              onMouseEnter={()=>setHover(n)} onClick={()=>setRating(rating===n?0:n)} title={n+' ดาว'}>
              <Icon name="star" size={24}/>
            </button>
          ))}
          {rating>0 && <span className="fb-star-lb">{rating}/5</span>}
        </div>
      </div>
      <div className="field">
        <label>{isReview ? 'ความเห็น' : 'ข้อความ'} <span className="hintl">{isReview ? `(จำเป็น · อย่างน้อย ${SB_REVIEW_MIN} ตัวอักษร)` : '(จำเป็น)'}</span></label>
        <textarea className="ta" rows={5} value={message} onChange={e=>setMessage(e.target.value)}
          placeholder={isReview ? 'ผลถอดปริมาณตรงกับแบบแค่ไหน ใช้งานสะดวกไหม อยากให้ปรับปรุงอะไร…' : 'เล่าปัญหาที่เจอ / สิ่งที่อยากให้เพิ่ม / สิ่งที่ชอบ…'} autoFocus/>
      </div>
      {status==='error' && (
        <div style={{marginTop:12,padding:'10px 14px',background:'#fef2f2',border:'1px solid #fecaca',
          borderRadius:8,fontSize:13,color:'#dc2626'}}>
          ⚠️ ส่งไม่สำเร็จ — {user ? 'ตรวจการเชื่อมต่ออินเทอร์เน็ตแล้วลองใหม่' : 'กรุณาเข้าสู่ระบบใหม่'}
        </div>
      )}
    </Modal>
  );
}

/* ---------- Province autocomplete (ช่องที่ตั้ง — พิมพ์แล้วขึ้นตัวเลือกจังหวัด) ---------- */
function ProvinceInput({ value, onChange, placeholder }){
  const [open,setOpen] = useState(false);
  const boxRef = useRef(null);
  const list = window.TH_PROVINCES || [];
  const q = (value||'').trim();
  const matches = q
    ? [...list.filter(p=>p.startsWith(q)), ...list.filter(p=>!p.startsWith(q)&&p.includes(q))].slice(0,8)
    : list.slice(0,12);
  useEffect(()=>{
    const h = e => { if(boxRef.current && !boxRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return ()=>document.removeEventListener('mousedown', h);
  },[]);
  const exact = list.includes(value);
  return (
    <div className="ac" ref={boxRef}>
      <input className="inp" value={value||''} placeholder={placeholder}
        onChange={e=>{ onChange(e.target.value); setOpen(true); }}
        onFocus={()=>setOpen(true)}/>
      {open && matches.length>0 && !(exact && matches.length===1) && (
        <div className="ac-dd scrollthin">
          {matches.map(p=>(
            <div key={p} className={'ac-item'+(p===value?' sel':'')}
              onMouseDown={e=>{ e.preventDefault(); onChange(p); setOpen(false); }}>{p}</div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---------- Confidence badge ---------- */
function ConfBadge({ c }) {
  if (!c) return <span className="conf conf-r">— ไม่พบ</span>;
  const b = confBand(c);
  return <span className={'conf conf-' + b}>{c}%</span>;
}

/* ===== Balloon animation ===== */
const BalloonCtx = createContext(()=>{});
function useBalloon(){ return useContext(BalloonCtx); }

function BalloonSVG({ color }){
  return (
    <svg width="38" height="54" viewBox="0 0 38 54" style={{display:'block'}}>
      <ellipse cx="19" cy="18" rx="17" ry="18" fill={color} opacity="0.92"/>
      <ellipse cx="12" cy="10" rx="4" ry="6" fill="white" opacity="0.22"/>
      <path d="M17 36 Q19 40 21 36" stroke={color} strokeWidth="2" fill="none" strokeLinecap="round"/>
      <path d="M19 40 Q16 46 19 52" stroke="#bbb" strokeWidth="1.5" fill="none" strokeLinecap="round"/>
    </svg>
  );
}

function PopBurst({ color }){
  const [out, setOut] = useState(false);
  useEffect(()=>{ const t=setTimeout(()=>setOut(true),30); return ()=>clearTimeout(t); },[]);
  return (
    <div style={{position:'relative',width:38,height:38}}>
      <div style={{
        position:'absolute',inset:0,borderRadius:'50%',background:color,
        transform: out?'scale(2.2)':'scale(0.4)',
        opacity: out?0:1,
        transition:'transform .4s ease-out, opacity .35s ease-out',
      }}/>
      {[0,45,90,135,180,225,270,315].map((ang,i)=>{
        const rad=ang*Math.PI/180, d=out?38+i*2:0;
        return (
          <div key={i} style={{
            position:'absolute',top:'50%',left:'50%',
            width:8,height:8,marginTop:-4,marginLeft:-4,
            borderRadius:'50%',background:i%2===0?color:'#fff',
            transform:`translate(${Math.cos(rad)*d}px,${Math.sin(rad)*d}px) scale(${out?0:1})`,
            opacity:out?0:1,
            transition:`transform ${.35+i*.025}s ease-out, opacity .45s ease-out`,
          }}/>
        );
      })}
    </div>
  );
}

function Balloon({ startX, delay, color, scale }){
  const totalMs = useRef(2300 + Math.random()*800).current;
  const popAt   = useRef(delay*1000 + totalMs*(0.60+Math.random()*0.22)).current;
  const [phase, setPhase] = useState('idle');

  useEffect(()=>{
    const t0 = setTimeout(()=>setPhase('rise'), delay*1000);
    const t1 = setTimeout(()=>setPhase('pop'),  popAt);
    const t2 = setTimeout(()=>setPhase('done'), popAt+700);
    return ()=>{ clearTimeout(t0); clearTimeout(t1); clearTimeout(t2); };
  }, []);

  if(phase==='idle'||phase==='done') return null;

  return (
    <div style={{
      position:'fixed', left:startX+'%', bottom:'-65px',
      pointerEvents:'none', zIndex:9999,
      animation:`balloonRise ${totalMs/1000}s linear forwards`,
    }}>
      <div style={{transform:`scale(${scale})`, animation:'balloonWobble 1.5s ease-in-out infinite'}}>
        {phase==='rise' && <BalloonSVG color={color}/>}
        {phase==='pop'  && <PopBurst   color={color}/>}
      </div>
    </div>
  );
}

function BalloonHost({ children }){
  const [balloons, setBalloons] = useState([]);
  const launchRef = useRef(null);
  launchRef.current = ()=>{
    const COLORS=['#ef4444','#3b82f6','#f59e0b','#10b981','#8b5cf6','#ec4899','#f97316'];
    const count = 3+Math.floor(Math.random()*2);
    const batch = Array.from({length:count},(_,i)=>({
      id: Date.now()+i,
      startX: 8+Math.random()*82,
      delay:  i*0.35+Math.random()*0.15,
      color:  COLORS[Math.floor(Math.random()*COLORS.length)],
      scale:  0.82+Math.random()*0.36,
    }));
    setBalloons(b=>[...b,...batch]);
    setTimeout(()=>setBalloons(b=>b.filter(x=>!batch.find(n=>n.id===x.id))),5800);
  };
  const launch = useMemo(()=>()=>launchRef.current(),[]);
  return (
    <BalloonCtx.Provider value={launch}>
      {children}
      {ReactDOM.createPortal(
        <div style={{position:'fixed',inset:0,pointerEvents:'none',zIndex:9999}}>
          {balloons.map(b=><Balloon key={b.id} startX={b.startX} delay={b.delay} color={b.color} scale={b.scale}/>)}
        </div>,
        document.body
      )}
    </BalloonCtx.Provider>
  );
}

/* ---------- Top-up modal (เติมเครดิต — อัปสลิป) ---------- */
const SLIP_STATUS = { pending:['รอตรวจสอบ','pending'], approved:['อนุมัติแล้ว','approved'], rejected:['ไม่อนุมัติ','rejected'] };
const SLIP_ERR = {   // รหัสจาก trigger payment_slips_guard_insert (migration 0009)
  too_many_pending_slips: 'มีสลิปรอตรวจสอบอยู่ 3 รายการแล้ว กรุณารอผู้ดูแลตรวจสอบก่อนส่งเพิ่ม',
  bad_amount: 'ยอดเงินไม่ถูกต้อง กรุณาตรวจสอบอีกครั้ง',
  bad_slip_path: 'อัปโหลดสลิปไม่สำเร็จ กรุณาลองใหม่อีกครั้ง',
};
function TopUpModal({ user, onClose, onSubmitted }){
  const toast = useToast();
  const TOPUP_PRICE = window.SB_CREDIT_PRICE || 890;   // บาท/เครดิต (1 เครดิต = 1 โปรเจกต์) — ตั้งที่ data.jsx
  const [qty,setQty] = useState(1);
  const [file,setFile] = useState(null);
  const [preview,setPreview] = useState(null);
  const [amount,setAmount] = useState(String(TOPUP_PRICE));
  const [busy,setBusy] = useState(false);
  const [slips,setSlips] = useState(null);   // ประวัติสลิปของฉัน (ล่าสุด 5)
  const total = TOPUP_PRICE * qty;
  const pickQty = (n) => { const q = Math.max(1, Math.min(99, n|0)); setQty(q); setAmount(String(TOPUP_PRICE * q)); };
  useEffect(()=>{
    let alive = true;
    if(user && window.getMySlips) window.getMySlips(user.id).then(({data})=>{ if(alive) setSlips(Array.isArray(data) ? data.slice(0,5) : []); }).catch(()=>{ if(alive) setSlips([]); });
    return ()=>{ alive = false; };
  },[user && user.id]);
  const pendingCount = (slips||[]).filter(s=>s.status==='pending').length;
  const onFile = (f) => { setFile(f||null); setPreview(f ? URL.createObjectURL(f) : null); };
  const copyAcct = async () => {
    try { await navigator.clipboard.writeText('1461622654'); toast('คัดลอกเลขบัญชีแล้ว ✓','check'); }
    catch(e){ toast('คัดลอกไม่ได้ — คัดลอกเลขบัญชีเองได้เลย'); }
  };
  const submit = async () => {
    if(!file){ toast('แนบรูปสลิปก่อน'); return; }
    if(pendingCount >= 3){ toast(SLIP_ERR.too_many_pending_slips); return; }
    setBusy(true);
    try {
      const up = await window.uploadSlipFile(user.id, file);
      if(up.error){ console.warn('slip upload:', up.error); toast('อัปโหลดสลิปไม่สำเร็จ กรุณาลองใหม่อีกครั้ง'); setBusy(false); return; }
      const { error } = await window.submitSlip({ userId:user.id, slipUrl:up.path, amount: amount?parseFloat(amount):null });
      if(error){
        console.warn('slip submit:', error);
        const code = Object.keys(SLIP_ERR).find(k => String(error.message||'').includes(k));
        toast(code ? SLIP_ERR[code] : 'ส่งสลิปไม่สำเร็จ กรุณาลองใหม่อีกครั้ง'); setBusy(false); return;
      }
      toast('ส่งสลิปแล้ว รอผู้ดูแลอนุมัติเติมเครดิต ✓','check');
      onSubmitted && onSubmitted(); onClose();
    } catch(e){ console.warn('slip:', e); toast('ส่งสลิปไม่สำเร็จ กรุณาตรวจสอบการเชื่อมต่อแล้วลองใหม่'); }
    setBusy(false);
  };
  return (
    <Modal title="เติมเครดิต" sub="โอนเงินแล้วแนบสลิป — ผู้ดูแลจะตรวจและเติมเครดิตให้" icon="star" onClose={onClose}
      foot={<><button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button>
        <button className="btn btn-primary" disabled={busy||!file} onClick={submit}>{busy?'กำลังส่ง…':'ส่งสลิป'}</button></>}>
      <div className="bank-box">
        <div className="bank-hd"><span className="bank-logo">K</span> โอนเงินมาที่บัญชีนี้</div>
        <div className="bank-rows">
          <div className="bank-r"><span className="bk">ธนาคาร</span><span className="bv">กสิกรไทย</span></div>
          <div className="bank-r"><span className="bk">เลขบัญชี</span><span className="bv mono">146-1-62265-4</span>
            <button className="bank-copy" onClick={copyAcct}><Icon name="copy" size={13}/> คัดลอก</button></div>
          <div className="bank-r"><span className="bk">ชื่อบัญชี</span><span className="bv">วิทวัส วิบูลย์กุล</span></div>
        </div>
        <div className="bank-total"><span>ยอดที่ต้องโอน</span><b>{total.toLocaleString()} <span className="unit">บาท</span></b></div>
        <div style={{textAlign:'right',fontSize:12,color:'var(--ink-4)',marginTop:2}}>= {qty} เครดิต · สร้างได้ {qty} โปรเจกต์ ({TOPUP_PRICE.toLocaleString()} บาท/โปรเจกต์)</div>
      </div>
      <div className="field"><label>จำนวนเครดิต</label>
        <div className="topup-qty">
          {[1,3,5].map(n=>(
            <button key={n} type="button" className={'chip'+(qty===n?' active':'')} onClick={()=>pickQty(n)}>{n} เครดิต</button>
          ))}
          <div className="topup-step">
            <button type="button" className="btn btn-ghost btn-sm" aria-label="ลดจำนวน" disabled={qty<=1} onClick={()=>pickQty(qty-1)}>−</button>
            <span className="mono">{qty}</span>
            <button type="button" className="btn btn-ghost btn-sm" aria-label="เพิ่มจำนวน" disabled={qty>=99} onClick={()=>pickQty(qty+1)}>+</button>
          </div>
        </div></div>
      <div className="field"><label>ยอดที่โอนจริง (บาท) <span className="hintl">(แก้ได้)</span></label>
        <div className="inp-money"><span className="cur">฿</span>
          <input className="inp mono" type="number" value={amount} onChange={e=>setAmount(e.target.value)} placeholder={`เช่น ${total}`}/></div></div>
      <div className="field"><label>รูปสลิป</label>
        <label className={"slip-drop"+(file?" has":"")}>
          <input type="file" accept="image/*" hidden onChange={e=>onFile((e.target.files&&e.target.files[0])||null)}/>
          {file ? (
            <div className="slip-drop-file">
              {preview && <img src={preview} className="slip-thumb" alt=""/>}
              <div className="slip-drop-meta">
                <div className="slip-drop-name">{file.name}</div>
                <div className="slip-drop-sub">แตะเพื่อเปลี่ยนรูป</div>
              </div>
              <span className="slip-ok"><Icon name="check" size={16}/></span>
            </div>
          ) : (
            <div className="slip-drop-empty">
              <span className="slip-drop-ic"><Icon name="upload" size={20}/></span>
              <b>แตะเพื่อเลือกรูปสลิป</b>
              <span className="slip-drop-hint">รองรับ JPG / PNG</span>
            </div>
          )}
        </label></div>
      <div className="topup-note"><Icon name="info" size={14}/> 1 เครดิต = 1 โปรเจกต์ · ผู้ดูแลเติมให้ตามยอดที่ตรวจสอบ</div>
      {slips && slips.length > 0 && (
        <div className="topup-hist">
          <div className="topup-hist-hd">สลิปที่ส่งล่าสุด</div>
          {slips.map(s=>{
            const st = SLIP_STATUS[s.status] || [s.status,'pending'];
            const d = s.created_at ? new Date(s.created_at) : null;
            return (
              <div key={s.id} className="topup-hist-r">
                <span className="mono">{d ? d.toLocaleDateString('th-TH',{day:'numeric',month:'short'})+' '+d.toLocaleTimeString('th-TH',{hour:'2-digit',minute:'2-digit'}) : '—'}</span>
                <span className="mono">{s.amount!=null ? Number(s.amount).toLocaleString()+' บาท' : '—'}</span>
                <span className={'slip-st '+st[1]}>{st[0]}{s.status==='approved' && s.credits_granted ? ` +${s.credits_granted}` : ''}</span>
              </div>
            );
          })}
        </div>
      )}
    </Modal>
  );
}

Object.assign(window, { Icon, StatusBadge, ToastHost, useToast, Modal, SideModal, Sidebar, Topbar, ConfBadge, TopUpModal,
  BalloonHost, useBalloon, useState, useEffect, useRef, useMemo });