/* ============================================================
   Icons (functional, line-based)
   ============================================================ */
const Icon = ({ name, size = 32, stroke = 2, color = "currentColor" }) => {
  const props = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: color, strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "arrow-right": return <svg {...props}><path d="M5 12h14M13 6l6 6-6 6"/></svg>;
    case "arrow-left": return <svg {...props}><path d="M19 12H5M11 6l-6 6 6 6"/></svg>;
    case "arrow-up-right": return <svg {...props}><path d="M7 17L17 7M7 7h10v10"/></svg>;
    case "check": return <svg {...props}><path d="M20 6L9 17l-5-5"/></svg>;
    case "x": return <svg {...props}><path d="M18 6L6 18M6 6l12 12"/></svg>;
    case "alert": return <svg {...props}><path d="M12 9v4M12 17h.01"/><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/></svg>;
    case "info": return <svg {...props}><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>;
    case "lock": return <svg {...props}><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>;
    case "user": return <svg {...props}><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>;
    case "card": return <svg {...props}><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20M6 15h4"/></svg>;
    case "iris": return <svg {...props}><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="4"/><circle cx="12" cy="12" r="1.2" fill="currentColor"/></svg>;
    case "cash": return <svg {...props}><rect x="2" y="6" width="20" height="12" rx="2"/><circle cx="12" cy="12" r="3"/><path d="M6 10v.01M18 14v.01"/></svg>;
    case "mix": return <svg {...props}><path d="M3 7l4-4 4 4M7 3v18M21 17l-4 4-4-4M17 21V3"/></svg>;
    case "qr": return <svg {...props}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><path d="M14 14h3v3M21 14v.01M14 21h.01M21 21v-4M17 17v.01"/></svg>;
    case "scan": return <svg {...props}><path d="M3 7V5a2 2 0 012-2h2M17 3h2a2 2 0 012 2v2M21 17v2a2 2 0 01-2 2h-2M7 21H5a2 2 0 01-2-2v-2M3 12h18"/></svg>;
    case "mail": return <svg {...props}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>;
    case "printer": return <svg {...props}><path d="M6 9V2h12v7M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8" rx="1"/></svg>;
    case "clock": return <svg {...props}><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>;
    case "graduation": return <svg {...props}><path d="M22 10L12 5 2 10l10 5 10-5z"/><path d="M6 12v5a6 3 0 0012 0v-5"/></svg>;
    case "school": return <svg {...props}><path d="M3 21V10l9-5 9 5v11M3 21h18M9 21v-6h6v6"/></svg>;
    case "help": return <svg {...props}><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 015.83 1c0 2-3 3-3 3M12 17h.01"/></svg>;
    case "language": return <svg {...props}><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15 15 0 010 20M12 2a15 15 0 000 20"/></svg>;
    case "refresh": return <svg {...props}><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"/></svg>;
    case "wifi-off": return <svg {...props}><path d="M1 1l22 22M16.72 11.06A10.94 10.94 0 0119 12.55M5 12.55a10.94 10.94 0 015.17-2.39M10.71 5.05A16 16 0 0122.58 9M1.42 9a15.91 15.91 0 014.7-2.88M8.53 16.11a6 6 0 016.95 0M12 20h.01"/></svg>;
    case "tools": return <svg {...props}><path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z"/></svg>;
    case "banknote-x": return <svg {...props}><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M8 10l8 4M16 10l-8 4"/></svg>;
    case "campus": return <svg {...props}><path d="M3 21h18M5 21V8l7-5 7 5v13M9 21v-8h6v8M10 8h.01M14 8h.01"/></svg>;
    case "shield-check": return <svg {...props}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/></svg>;
    case "menu": return <svg {...props}><path d="M3 6h18M3 12h18M3 18h18"/></svg>;
    case "eye-off": return <svg {...props}><path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19M14.12 14.12a3 3 0 11-4.24-4.24M1 1l22 22"/></svg>;
    case "delete": return <svg {...props}><path d="M21 4H8l-7 8 7 8h13a2 2 0 002-2V6a2 2 0 00-2-2zM18 9l-6 6M12 9l6 6"/></svg>;
    default: return <svg {...props}><circle cx="12" cy="12" r="10"/></svg>;
  }
};
window.Icon = Icon;

/* ============================================================
   Logo (MC GR Portrait)
   ============================================================ */
const MCLogo = ({ height = 96, white = false }) => (
  <img
    src="assets/mc-logo-gr-portrait.svg"
    alt="Μητροπολιτικό Κολλέγιο"
    style={{ height: height + 'px', filter: white ? 'brightness(0) invert(1)' : 'none', display: 'block' }}
  />
);
window.MCLogo = MCLogo;

/* ============================================================
   Header — three variants: brand, compact, minimal
   ============================================================ */
const Header = ({ variant = "brand", showSteps = false, step = 0, totalSteps = 5, onCancel, hideLang = false, leftAction, rightAction }) => {
  const t = useT();
  const lang = window.AppState.lang;
  const setLang = window.AppState.setLang;
  const cls = variant === "compact" ? "screen-header compact" : variant === "minimal" ? "screen-header minimal" : "screen-header";

  return (
    <header className={cls}>
      <div className="screen-header-row">
        <div className="screen-header-logo">
          {leftAction || <MCLogo height={variant === "compact" ? 80 : 96} white={variant !== "minimal"} />}
        </div>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
          {rightAction}
          {!hideLang && (
            <div className="lang-toggle">
              <button className={lang === 'el' ? 'active' : ''} onClick={() => setLang('el')}>EL</button>
              <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
            </div>
          )}
          {onCancel && (
            <button className="btn-sm" onClick={onCancel} style={{ borderColor: variant === 'minimal' ? 'var(--n-300)' : 'rgba(255,255,255,.4)', color: variant === 'minimal' ? 'var(--mc-ink)' : '#fff', background: 'transparent' }}>
              <Icon name="x" size={20} /> {t.cancel}
            </button>
          )}
        </div>
      </div>
      {showSteps && (
        <div className="steps" style={{ marginTop: 48 }}>
          {Array.from({ length: totalSteps }).map((_, i) => (
            <div key={i} className={`steps-dot ${i < step ? 'done' : i === step ? 'active' : ''}`} />
          ))}
        </div>
      )}
    </header>
  );
};
window.Header = Header;

/* ============================================================
   Big touch button — mirrors attached home screen vibe
   ============================================================ */
const BigButton = ({ children, onClick, variant = "primary", icon, disabled }) => (
  <button className={`btn btn--${variant} btn--full`} onClick={onClick} disabled={disabled} style={disabled ? { opacity: 0.4, pointerEvents: 'none' } : {}}>
    {icon && <span style={{ display: 'inline-flex', marginRight: 8 }}><Icon name={icon} size={32} stroke={2} /></span>}
    <span style={{ flex: 1, textAlign: 'left' }}>{children}</span>
    <span className="btn-arrow"><Icon name="arrow-up-right" size={28} stroke={2.5} /></span>
  </button>
);
window.BigButton = BigButton;

/* ============================================================
   Option tile (for two- or three-up choices)
   ============================================================ */
const OptionTile = ({ icon, title, sub, selected, onClick, badge }) => (
  <button className={`option-tile ${selected ? 'selected' : ''}`} onClick={onClick}>
    <div className="option-tile-icon"><Icon name={icon} size={48} stroke={1.8} /></div>
    <div className="option-tile-text">
      <div className="option-tile-title">{title}</div>
      <div className="option-tile-sub">{sub}</div>
    </div>
    {badge && <div style={{ background: 'var(--mc-red)', color: '#fff', padding: '6px 14px', borderRadius: 999, fontSize: 16, fontWeight: 600 }}>{badge}</div>}
    <div className="option-tile-arrow"><Icon name="arrow-right" size={28} /></div>
  </button>
);
window.OptionTile = OptionTile;

/* ============================================================
   Status panel (success / error / warning / info)
   ============================================================ */
const StatusPanel = ({ kind = "success", icon, title, sub, children }) => (
  <div className="status-panel fade-in">
    <div className={`status-icon ${kind}`}>
      <Icon name={icon || (kind === 'success' ? 'check' : kind === 'error' ? 'x' : 'alert')} size={104} stroke={2.5} />
    </div>
    <h2 className="t-h1" style={{ margin: '0 0 24px' }}>{title}</h2>
    {sub && <p className="t-body-lg t-muted" style={{ maxWidth: 1100, margin: '0 0 56px', textAlign: 'center' }}>{sub}</p>}
    {children}
  </div>
);
window.StatusPanel = StatusPanel;

/* ============================================================
   Numeric keypad (large kiosk-friendly)
   ============================================================ */
const Keypad = ({ onKey, onDelete, onClear, onSubmit, submitLabel = "OK", canSubmit = true }) => {
  const t = useT();
  return (
    <div className="keypad">
      {[1,2,3,4,5,6,7,8,9].map(n => (
        <button key={n} onClick={() => onKey(String(n))}>{n}</button>
      ))}
      <button className="danger" onClick={onClear}><Icon name="x" size={32} /></button>
      <button onClick={() => onKey('0')}>0</button>
      <button onClick={onDelete}><Icon name="delete" size={32} /></button>
      <button className="action" style={{ gridColumn: '1 / -1' }} onClick={onSubmit} disabled={!canSubmit}>
        {submitLabel}
      </button>
    </div>
  );
};
window.Keypad = Keypad;

/* ============================================================
   QR placeholder — generated SVG pattern (deterministic)
   ============================================================ */
const QRPlaceholder = ({ seed = "MC" }) => {
  const size = 25;
  const cells = React.useMemo(() => {
    let h = 0;
    for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) | 0;
    const grid = [];
    for (let y = 0; y < size; y++) {
      const row = [];
      for (let x = 0; x < size; x++) {
        // fixed-position blocks for QR markers
        const isFinder = (x < 7 && y < 7) || (x > size - 8 && y < 7) || (x < 7 && y > size - 8);
        if (isFinder) {
          const fx = x < 7 ? x : x - (size - 7);
          const fy = y < 7 ? y : y - (size - 7);
          const onEdge = fx === 0 || fx === 6 || fy === 0 || fy === 6;
          const onCenter = fx >= 2 && fx <= 4 && fy >= 2 && fy <= 4;
          row.push(onEdge || onCenter);
        } else {
          h = (h * 1103515245 + 12345) | 0;
          row.push(((h >>> 16) & 1) === 1);
        }
      }
      grid.push(row);
    }
    return grid;
  }, [seed]);
  const cellSize = 100 / size;
  return (
    <svg className="qr-svg" viewBox={`0 0 100 100`}>
      {cells.flatMap((row, y) => row.map((on, x) => on && (
        <rect key={`${x}-${y}`} x={x * cellSize} y={y * cellSize} width={cellSize + 0.5} height={cellSize + 0.5} fill="#1A1A1A"/>
      )))}
    </svg>
  );
};
window.QRPlaceholder = QRPlaceholder;

/* ============================================================
   Pulsing scan target (kiosk-style "place code here" indicator)
   ============================================================ */
const ScanTarget = ({ icon = "qr" }) => (
  <div style={{ width: 360, height: 360, borderRadius: 32, background: 'var(--n-50)', border: '3px dashed var(--n-300)', display: 'grid', placeItems: 'center', position: 'relative' }}>
    <div style={{ position: 'absolute', inset: 32, borderRadius: 16, background: 'var(--n-0)', boxShadow: 'inset 0 0 0 2px var(--n-200)', display: 'grid', placeItems: 'center' }}>
      <Icon name={icon} size={140} stroke={1.5} color="var(--n-400)" />
    </div>
    <div style={{ position: 'absolute', top: 0, left: 0, width: 60, height: 60, borderTop: '6px solid var(--mc-red)', borderLeft: '6px solid var(--mc-red)', borderTopLeftRadius: 32 }}/>
    <div style={{ position: 'absolute', top: 0, right: 0, width: 60, height: 60, borderTop: '6px solid var(--mc-red)', borderRight: '6px solid var(--mc-red)', borderTopRightRadius: 32 }}/>
    <div style={{ position: 'absolute', bottom: 0, left: 0, width: 60, height: 60, borderBottom: '6px solid var(--mc-red)', borderLeft: '6px solid var(--mc-red)', borderBottomLeftRadius: 32 }}/>
    <div style={{ position: 'absolute', bottom: 0, right: 0, width: 60, height: 60, borderBottom: '6px solid var(--mc-red)', borderRight: '6px solid var(--mc-red)', borderBottomRightRadius: 32 }}/>
  </div>
);
window.ScanTarget = ScanTarget;

/* ============================================================
   Footer/secure label
   ============================================================ */
const SecureFooter = () => {
  const t = useT();
  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 24, padding: '24px 0', color: 'var(--n-500)', fontSize: 16 }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><Icon name="lock" size={18} /> {t.secured}</span>
      <span>·</span>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><Icon name="shield-check" size={18} /> {t.classter}</span>
    </div>
  );
};
window.SecureFooter = SecureFooter;

/* ============================================================
   Money formatting
   ============================================================ */
window.fmtEUR = (n, lang = 'el') => {
  const formatted = new Intl.NumberFormat(lang === 'el' ? 'el-GR' : 'en-GB', { style: 'currency', currency: 'EUR', minimumFractionDigits: 2 }).format(n);
  return formatted;
};

/* ============================================================
   Modal
   ============================================================ */
const Modal = ({ children, onClose }) => (
  <div className="modal-backdrop fade-in" onClick={onClose}>
    <div className="modal" onClick={e => e.stopPropagation()}>{children}</div>
  </div>
);
window.Modal = Modal;
