// Prodz — shared chrome: icons, navigation context, global top bar, helpers.
const { createContext: createCtxS, useContext: useCtxS, useState: useStateS, useRef: useRefS, useEffect: useEffectS } = React;

const USER_AVATAR = 'assets/imagery/prod-thumb-1.jpg';

// Lucide icon → inline SVG.
function Ic({ n, s = 22, color = 'currentColor', strokeWidth = 2, fill = 'none' }) {
  const node = (window.lucide && lucide.icons && lucide.icons[n]);
  if (!node) return null;
  const svg = lucide.createElement(node).outerHTML
    .replace('<svg ', `<svg width="${s}" height="${s}" stroke="${color}" fill="${fill}" stroke-width="${strokeWidth}" `);
  return <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }} dangerouslySetInnerHTML={{ __html: svg }} />;
}

// ---- Navigation context: shared by every screen + the top/bottom bars ----
const NavContext = createCtxS(null);
function useNav() { return useCtxS(NavContext); }

// ---- Home tweaks context: live values from the Tweaks panel (App.jsx) ----
const TweaksContext = createCtxS({});
function useHomeTweaks() { return useCtxS(TweaksContext); }

// ---- Compact language toggle (IT | EN) ----
function LangToggle({ compact = true }) {
  const { lang, setLang } = useL();
  const opt = (id, label) => (
    <button onClick={() => setLang(id)} key={id}
      style={{
        border: 'none', cursor: 'pointer', padding: compact ? '0 8px' : '0 12px',
        height: compact ? 26 : 32, borderRadius: 'var(--radius-pill)',
        fontFamily: 'var(--font-ui)', fontSize: compact ? 11 : 13, fontWeight: 700, letterSpacing: '0.04em',
        background: lang === id ? 'var(--surface-raised)' : 'transparent',
        color: lang === id ? 'var(--text-primary)' : 'var(--text-subtle)',
        boxShadow: lang === id ? 'var(--ring-inset-hairline)' : 'none',
        transition: 'all var(--dur-base) var(--ease-standard)',
      }}>{label}</button>
  );
  return (
    <div style={{ display: 'inline-flex', gap: 2, padding: 2, background: 'var(--surface-card)', borderRadius: 'var(--radius-pill)', boxShadow: 'var(--ring-inset-hairline)' }}>
      {opt('it', 'IT')}{opt('en', 'EN')}
    </div>
  );
}

// ---- Global top bar ----
// Detail screens: back + title (left) · actions/profile (right).
// Main tabs: notifications + messages/create (left) · centered wordmark · profile (right).
// Which of [messages, create] sits up here vs. in the bottom-nav center is
// driven by the `ctaSlot` tweak — they swap as a pair.
function TopBar({ title, onBack, sticky = true, showLang = true, actions = null }) {
  const nav = useNav();
  const { L } = useL();
  const tweaks = useHomeTweaks();
  const ctaSlot = (tweaks && tweaks.ctaSlot) || 'plus';

  const headerStyle = {
    position: sticky ? 'sticky' : 'relative', top: 0, zIndex: 30,
    display: 'flex', alignItems: 'center', gap: 8,
    padding: '0 14px', height: 58, flexShrink: 0,
    background: 'var(--surface-chrome)', backdropFilter: 'var(--blur-chrome)', WebkitBackdropFilter: 'var(--blur-chrome)',
    borderBottom: '1px solid var(--border-hairline)',
  };

  // --- Detail screens: unchanged 2-column layout ---
  if (onBack) {
    return (
      <div style={{ ...headerStyle, justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
          <button onClick={onBack} aria-label="Back" style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-body)', display: 'flex', padding: 4, marginLeft: -4 }}>
            <Ic n="ChevronLeft" s={24} />
          </button>
          <span style={{ fontFamily: 'var(--font-ui)', fontWeight: 700, fontSize: 13, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {actions ? actions : (
          <>
          <button onClick={() => nav.openInbox()} aria-label="Inbox" style={chromeBtn}>
            <Ic n="Send" s={19} />
            {nav.inboxCount > 0 && <span style={badgeDot}>{nav.inboxCount}</span>}
          </button>
          <button onClick={() => nav.openProfile('me')} aria-label="Profile" style={{ ...chromeBtn, padding: 0, overflow: 'hidden' }}>
            <img src={USER_AVATAR} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          </button>
          </>
          )}
        </div>
      </div>
    );
  }

  // --- Main tabs: 3-column, centered wordmark ---
  const msgBtn = (
    <button key="msg" onClick={() => nav.openInbox()} aria-label={L('Messaggi', 'Messages')} style={chromeBtn}>
      <Ic n="Send" s={18} />
      {nav.inboxCount > 0 && <span style={badgeDot}>{nav.inboxCount}</span>}
    </button>
  );
  const createBtn = (
    <button key="create" onClick={() => nav.goTab('add')} aria-label={L('Crea', 'Create')} style={chromeBtn}>
      <Ic n="Plus" s={20} />
    </button>
  );

  return (
    <div style={{ ...headerStyle, justifyContent: 'space-between', position: sticky ? 'sticky' : 'relative' }}>
      {/* left — notifications + (messages | create) */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, zIndex: 1 }}>
        <button onClick={() => nav.openActivity && nav.openActivity()} aria-label={L('Notifiche', 'Notifications')} style={chromeBtn}>
          <Ic n="Bell" s={18} />
          <span style={{ position: 'absolute', top: 7, right: 8, width: 7, height: 7, borderRadius: '50%', background: 'var(--prodz-teal)', boxShadow: '0 0 0 2px var(--surface-raised)' }} />
        </button>
        {ctaSlot === 'plus' ? msgBtn : createBtn}
      </div>

      {/* center — wordmark */}
      <span style={{ position: 'absolute', left: '50%', transform: 'translateX(-50%)', display: 'inline-flex', alignItems: 'center', gap: 2, fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 22, letterSpacing: '-0.03em', color: 'var(--text-primary)', pointerEvents: 'none' }}>
        Prodz<span style={{ color: 'var(--prodz-teal)' }}>.</span>
      </span>

      {/* right — profile */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, zIndex: 1 }}>
        <button onClick={() => nav.openProfile('me')} aria-label="Profile" style={{ ...chromeBtn, padding: 0, overflow: 'hidden' }}>
          <img src={USER_AVATAR} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
        </button>
      </div>
    </div>
  );
}

const chromeBtn = {
  position: 'relative', width: 38, height: 38, borderRadius: '50%', border: 'none', cursor: 'pointer',
  background: 'var(--surface-raised)', color: 'var(--text-body)', boxShadow: 'var(--ring-inset-hairline)',
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
};
const badgeDot = {
  position: 'absolute', top: -3, right: -3, minWidth: 17, height: 17, padding: '0 4px',
  borderRadius: 'var(--radius-pill)', background: 'var(--prodz-gold)', color: 'var(--text-on-accent)',
  fontFamily: 'var(--font-ui)', fontSize: 9, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center',
  boxShadow: '0 0 0 2px var(--surface-canvas)',
};

// ---- Section row: eyebrow header + optional action, standard gutter ----
function Section({ title, action, onAction, children, style = {} }) {
  const { SectionHeader } = window.ProdzDesignSystem_d0b87b;
  return (
    <section style={{ marginTop: 26, ...style }}>
      <div style={{ padding: '0 16px' }}>
        <SectionHeader title={title} action={action} onAction={onAction} />
      </div>
      {children}
    </section>
  );
}

// ---- Bottom sheet (confirmation / compose) ----
function Sheet({ open, onClose, children }) {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 60, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
      background: 'var(--overlay)', animation: 'pz-fade 180ms var(--ease-standard) both',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: 'var(--surface-card)', borderTopLeftRadius: 22, borderTopRightRadius: 22,
        boxShadow: '0 -20px 50px -10px rgba(0,0,0,0.7)', borderTop: '1px solid var(--hairline-strong)',
        padding: '10px 16px calc(20px + env(safe-area-inset-bottom))', animation: 'pz-fade-up 240ms var(--ease-out) both',
      }}>
        <div style={{ width: 38, height: 4, borderRadius: 2, background: 'var(--ink-700)', margin: '4px auto 14px' }} />
        {children}
      </div>
    </div>
  );
}

// ---- Toast (transient confirmation, e.g. Undo) ----
function Toast({ toast, onAction }) {
  if (!toast) return null;
  return (
    <div style={{
      position: 'absolute', left: 16, right: 16, bottom: 80, zIndex: 55,
      display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
      background: 'var(--ink-700)', borderRadius: 'var(--radius-md)', boxShadow: 'var(--shadow-xl), var(--ring-inset-hairline)',
      animation: 'pz-fade-up 220ms var(--ease-out) both',
    }}>
      <span style={{ flex: 1, fontFamily: 'var(--font-ui)', fontSize: 13, color: 'var(--text-body)' }}>{toast.msg}</span>
      {toast.actionLabel && (
        <button onClick={onAction} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--prodz-teal)', fontFamily: 'var(--font-ui)', fontSize: 13, fontWeight: 700 }}>{toast.actionLabel}</button>
      )}
    </div>
  );
}

// ---- Tiny eyebrow label ----
function Eyebrow({ children, color = 'var(--text-subtle)', style = {} }) {
  return <div style={{ fontFamily: 'var(--font-ui)', fontSize: 10, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color, ...style }}>{children}</div>;
}

Object.assign(window, {
  Ic, NavContext, useNav, TweaksContext, useHomeTweaks, LangToggle, TopBar, Section, Sheet, Toast, Eyebrow, USER_AVATAR,
  // expose React hook aliases so sibling Babel scripts resolve them at call time
  useStateS, useRefS, useEffectS, useCtxS, createCtxS,
});
