// src/f-shared.jsx — Option F shared components
// Header, Hero image, Title with italic fragment, Section-aware ingredients.
// Used by all viewport variants (desktop / tablet / mobile).

// Artboard surface — wraps each F screen with the dark theme class.
const ArtboardSurface = ({ children, padding = 56, bg = 'var(--paper)', dark = false, theme = 'f', style }) => (
  <div className={`lc ${dark ? 'lc-dark' : ''} ${theme ? 'lc-theme-' + theme : ''}`} style={{
    width: '100%', height: '100%',
    background: bg,
    padding,
    overflow: 'hidden',
    ...style,
  }}>{children}</div>
);

// Real photo path — committed asset
const FPHOTO = 'assets/sichuan-chicken.png';

// ─── F · Wordmark ───────────────────────────────────────────────
const FWordmark = ({ size = 26 }) => (
  <div style={{ display: 'inline-flex', alignItems: 'baseline', gap: 4 }}>
    <span style={{
      fontFamily: 'Bricolage Grotesque', fontWeight: 700,
      fontSize: size, color: 'var(--ink)',
      letterSpacing: '-0.045em',
      lineHeight: 1,
    }}>luis</span>
    <span style={{
      fontFamily: 'Spectral', fontWeight: 500, fontStyle: 'italic',
      fontSize: size, color: 'var(--olive)',
      letterSpacing: '-0.015em',
      lineHeight: 1,
    }}>cooks.</span>
  </div>
);

// ─── F · Display title with italic flavour fragment ─────────────
const FTitle = ({ name, size = 108, lineHeight = 0.9, color = 'var(--ink)',
  italicColor = 'var(--olive)', breakBeforeWith = true }) => {
  const m = name.match(/^(.+?)(\s+with\s+.+?)(\.|$)/i);
  if (!m) {
    return (
      <h1 style={{
        fontFamily: 'Bricolage Grotesque', fontWeight: 700,
        fontSize: size, lineHeight, letterSpacing: '-0.045em',
        color, margin: 0,
      }}>{name}<span style={{ color: italicColor }}>.</span></h1>
    );
  }
  return (
    <h1 style={{
      fontFamily: 'Bricolage Grotesque', fontWeight: 700,
      fontSize: size, lineHeight, letterSpacing: '-0.045em',
      color, margin: 0,
    }}>{m[1]}{breakBeforeWith && <br/>}
      <span style={{
        fontFamily: 'Spectral', fontStyle: 'italic',
        fontWeight: 400, color: italicColor,
        letterSpacing: '-0.02em',
      }}>{breakBeforeWith ? m[2].trim() : m[2]}.</span></h1>
  );
};

// ─── F · Nav (desktop / tablet) ─────────────────────────────────
const FNav = ({ active = 'Recipes', compact = false }) => (
  <nav style={{ display: 'flex', gap: 6, padding: 4,
    background: 'rgba(255,255,255,0.04)', borderRadius: 999,
    border: '1px solid var(--hairline)' }}>
    {[
      { l: 'Recipes' },
      { l: 'Cook', soon: true },
      { l: 'Plan', soon: true },
      { l: 'Groceries', soon: true },
    ].map((n) => {
      const isActive = active === n.l;
      return (
        <span key={n.l} style={{
          fontFamily: 'Bricolage Grotesque',
          fontSize: compact ? 11 : 12, fontWeight: 500,
          padding: compact ? '6px 11px' : '7px 14px', borderRadius: 999,
          background: isActive
            ? 'linear-gradient(180deg, rgba(255,255,255,0.10), rgba(255,255,255,0.02))'
            : 'transparent',
          border: isActive ? '1px solid rgba(255,255,255,0.14)' : '1px solid transparent',
          color: isActive ? 'var(--ink)' : 'var(--ink-3)',
          display: 'inline-flex', alignItems: 'baseline', gap: 4,
          whiteSpace: 'nowrap',
        }}>{n.l}
          {n.soon && <span style={{ fontFamily: 'Spectral', fontStyle: 'italic',
            fontSize: 10, color: 'var(--olive)' }}>soon</span>}
        </span>
      );
    })}
  </nav>
);

// Avatar — the "L" gradient pill
const FAvatar = ({ size = 34, initial = 'L' }) => (
  <div style={{
    width: size, height: size, borderRadius: 999,
    background: 'linear-gradient(135deg, #f0a850 0%, #b06820 100%)',
    color: '#1a1208',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontFamily: 'Bricolage Grotesque', fontWeight: 700, fontSize: size * 0.42,
    boxShadow: '0 4px 14px rgba(240,168,80,0.30), inset 0 1px 0 rgba(255,255,255,0.3)',
    flexShrink: 0,
  }}>{initial}</div>
);

// ─── F · Desktop / tablet header ─────────────────────────────────
const FHeader = ({ active = 'Recipes' }) => (
  <header style={{
    display: 'flex', alignItems: 'center', gap: 32,
    padding: '20px 48px',
    borderBottom: '1px solid var(--hairline)',
    position: 'relative', zIndex: 2,
  }}>
    <FWordmark />
    <div style={{ marginLeft: 24 }}><FNav active={active} /></div>
    <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 18 }}>
      <Icon.search size={18} style={{ color: 'var(--ink-3)' }} />
      <span style={{ width: 1, height: 22, background: 'var(--hairline)' }} />
      <FAvatar />
    </div>
  </header>
);

// ─── F · Mobile header (just wordmark + hamburger + avatar) ──────
const FMobileHeader = () => (
  <header style={{
    display: 'flex', alignItems: 'center', gap: 12,
    padding: '14px 18px',
    borderBottom: '1px solid var(--hairline)',
    position: 'relative', zIndex: 2,
  }}>
    <FWordmark size={22} />
    <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 12 }}>
      <Icon.search size={20} style={{ color: 'var(--ink-2)' }} />
      <FAvatar size={32} />
    </div>
  </header>
);

// ─── F · Mobile bottom nav ─────────────────────────────────────
const FMobileBottomNav = ({ active = 'Recipes' }) => (
  <nav style={{
    display: 'grid',
    gridTemplateColumns: 'repeat(4, 1fr)',
    gap: 0,
    padding: '8px 12px 14px',
    borderTop: '1px solid var(--hairline)',
    background: 'rgba(10,10,12,0.85)',
    backdropFilter: 'blur(20px)',
    position: 'sticky', bottom: 0,
  }}>
    {[
      { l: 'Recipes', icon: <Icon.bookmark size={20} /> },
      { l: 'Cook', icon: <Icon.flame size={20} />, soon: true },
      { l: 'Plan', icon: <Icon.list size={20} />, soon: true },
      { l: 'Groceries', icon: <Icon.upload size={20} />, soon: true },
    ].map((n) => {
      const isActive = active === n.l;
      return (
        <button key={n.l} style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          padding: '6px 4px',
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
          color: isActive ? 'var(--olive)' : 'var(--ink-3)',
          position: 'relative',
        }}>
          {n.icon}
          <span style={{
            fontFamily: 'Bricolage Grotesque', fontSize: 10, fontWeight: 600,
            letterSpacing: '0.04em',
          }}>{n.l}</span>
          {n.soon && <span style={{
            position: 'absolute', top: 0, right: '20%',
            width: 5, height: 5, borderRadius: 999,
            background: 'var(--olive)', opacity: 0.6,
          }} />}
        </button>
      );
    })}
  </nav>
);

// ─── F · Hero image — the real photo ────────────────────────────
const FHeroImage = ({ height, radius = 18, src = FPHOTO, alt = 'sichuan cold chicken',
  overlay = true, badge = true, style = {} }) => (
  <div style={{
    position: 'relative', height,
    borderRadius: radius, overflow: 'hidden',
    boxShadow: '0 30px 80px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.04)',
    ...style,
  }}>
    <img src={src} alt={alt} style={{
      width: '100%', height: '100%', objectFit: 'cover', display: 'block',
    }} />
    {overlay && (
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'linear-gradient(180deg, rgba(0,0,0,0.18) 0%, transparent 25%, transparent 65%, rgba(0,0,0,0.35) 100%)' }} />
    )}
    {badge && (
      <div style={{ position: 'absolute', top: 16, right: 16 }}>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '7px 12px', borderRadius: 999,
          background: 'rgba(12,12,14,0.7)',
          backdropFilter: 'blur(10px)',
          border: '1px solid rgba(255,255,255,0.12)',
          fontFamily: 'Bricolage Grotesque', fontSize: 10, fontWeight: 600,
          letterSpacing: '0.20em', textTransform: 'uppercase',
          color: 'var(--ink-2)',
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 999,
            background: 'var(--olive)' }} />
          Enhanced
        </span>
      </div>
    )}
  </div>
);

// ─── F · Section-aware ingredient groups ────────────────────────
const FIngredients = ({ ingredients, mode = 'view', checked = new Set(),
  activeGroupTitle = null }) => {
  // Parse into groups by "For …:" headers
  const groups = [];
  let current = { title: null, items: [] };
  ingredients.forEach((line) => {
    if (line === '') return;
    if (line.endsWith(':')) {
      if (current.items.length || current.title) groups.push(current);
      current = { title: line.replace(':', ''), items: [] };
    } else {
      current.items.push(line);
    }
  });
  if (current.items.length) groups.push(current);

  if (groups.length === 1 && !groups[0].title) {
    return (
      <ul style={{ listStyle: 'none', padding: 0, margin: 0,
        display: 'flex', flexDirection: 'column', gap: 2 }}>
        {groups[0].items.map((line, i) => (
          <FIngredientRow key={i} line={line}
            checked={checked.has(line)} mode={mode} />
        ))}
      </ul>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {groups.map((g, gi) => {
        const isActive = mode === 'cook' && activeGroupTitle &&
          g.title && g.title.toLowerCase().includes(activeGroupTitle.toLowerCase());
        return (
          <div key={gi} style={{
            padding: g.title ? '18px 20px 16px' : 0,
            background: g.title
              ? (isActive ? 'rgba(240,168,80,0.06)' : 'rgba(255,255,255,0.025)')
              : 'transparent',
            border: g.title
              ? (isActive ? '1px solid rgba(240,168,80,0.30)' : '1px solid var(--hairline)')
              : 'none',
            borderRadius: 14,
          }}>
            {g.title && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10,
                marginBottom: 12 }}>
                <span style={{
                  fontFamily: 'Bricolage Grotesque', fontSize: 10,
                  fontWeight: 600, letterSpacing: '0.28em', textTransform: 'uppercase',
                  color: 'var(--olive)',
                }}>{g.title.replace(/^For\s+(the\s+)?/i, '').trim() || g.title}</span>
                <span style={{ flex: 1, height: 1, background: 'var(--hairline-2)' }} />
                <span style={{ fontFamily: 'var(--mono)', fontSize: 10,
                  color: 'var(--ink-3)', letterSpacing: '0.04em' }}>
                  {g.items.length} items
                </span>
              </div>
            )}
            <ul style={{ listStyle: 'none', padding: 0, margin: 0,
              display: 'flex', flexDirection: 'column', gap: 2 }}>
              {g.items.map((line, i) => (
                <FIngredientRow key={i} line={line}
                  checked={checked.has(line)} mode={mode}
                  highlight={isActive && !checked.has(line)} />
              ))}
            </ul>
          </div>
        );
      })}
    </div>
  );
};

const FIngredientRow = ({ line, checked, mode = 'view', highlight }) => {
  if (mode === 'view') {
    return (
      <li style={{ display: 'flex', alignItems: 'baseline', gap: 12,
        padding: '6px 0' }}>
        <span style={{ width: 4, height: 4, borderRadius: 999,
          background: 'var(--olive)', flexShrink: 0,
          marginTop: 9, opacity: 0.7 }} />
        <span style={{ fontFamily: 'Spectral', fontSize: 17, lineHeight: 1.5,
          color: 'var(--ink)' }}>{line}</span>
      </li>
    );
  }
  return (
    <li>
      <label style={{
        display: 'flex', alignItems: 'flex-start', gap: 12,
        padding: '10px 4px', cursor: 'pointer',
      }}>
        <span style={{
          width: 22, height: 22, borderRadius: 5, marginTop: 1, flexShrink: 0,
          border: checked ? 'none' : '1.5px solid var(--ink-3)',
          background: checked
            ? 'linear-gradient(135deg, #f0a850, #c97818)'
            : 'transparent',
          color: '#1a1208',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{checked && <Icon.check size={13} stroke={3} />}</span>
        <span style={{
          fontFamily: 'Spectral', fontSize: 17, lineHeight: 1.45,
          color: checked ? 'var(--ink-3)' : 'var(--ink)',
          textDecoration: checked ? 'line-through' : 'none',
          fontWeight: highlight ? 500 : 400,
        }}>{line}</span>
      </label>
    </li>
  );
};

// ─── F · Amber primary CTA ───────────────────────────────────────
const FButton = ({ children, size = 'm', variant = 'amber', style, onClick }) => {
  const sizes = {
    s: { font: 13, pad: '10px 16px' },
    m: { font: 15, pad: '14px 22px' },
    l: { font: 17, pad: '18px 28px' },
    xl: { font: 18, pad: '20px 32px' },
  };
  const s = sizes[size];
  const variants = {
    amber: {
      background: 'linear-gradient(180deg, #f0a850, #c97818)',
      color: '#1a1208',
      boxShadow: '0 10px 28px rgba(240,168,80,0.30), inset 0 1px 0 rgba(255,255,255,0.35)',
      border: 'none',
    },
    ghost: {
      background: 'rgba(255,255,255,0.04)',
      color: 'var(--ink-2)',
      border: '1px solid var(--hairline)',
      boxShadow: 'none',
    },
    quiet: {
      background: 'transparent',
      color: 'var(--ink-2)',
      border: '1px solid var(--hairline)',
      boxShadow: 'none',
    },
  };
  return (
    <button onClick={onClick} style={{
      fontFamily: 'Bricolage Grotesque', fontWeight: 600,
      fontSize: s.font, padding: s.pad, borderRadius: 999,
      cursor: 'pointer',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      ...variants[variant],
      ...style,
    }}>{children}</button>
  );
};

// ─── F · Pill row (timers, tags, etc.) ──────────────────────────
const FPill = ({ children, accent, style }) => (
  <span style={{
    display: 'inline-flex', alignItems: 'center', gap: 8,
    padding: '7px 12px', borderRadius: 999,
    background: accent ? 'rgba(240,168,80,0.10)' : 'rgba(255,255,255,0.04)',
    border: accent ? '1px solid rgba(240,168,80,0.30)' : '1px solid var(--hairline)',
    fontFamily: 'Bricolage Grotesque', fontSize: 11, fontWeight: 500,
    color: accent ? 'var(--olive)' : 'var(--ink-2)',
    whiteSpace: 'nowrap',
    ...style,
  }}>{children}</span>
);

// ─── F · Recipe card (for library) ──────────────────────────────
const FRecipeCard = ({ recipe, photoSrc, size = 'm' }) => {
  const r = recipe;
  // Decide title display
  const m = r.name.match(/^(.+?)(\s+with\s+.+?)(\.|$)/i);

  return (
    <div style={{
      display: 'flex', flexDirection: 'column', gap: 12,
      cursor: 'pointer',
    }}>
      <div style={{
        position: 'relative', aspectRatio: '4 / 5',
        borderRadius: 14, overflow: 'hidden',
        background: r.bg || '#1a1610',
        boxShadow: '0 12px 28px rgba(0,0,0,0.35), 0 0 0 1px rgba(255,255,255,0.04)',
      }}>
        {photoSrc ? (
          <img src={photoSrc} alt={r.name} style={{
            width: '100%', height: '100%', objectFit: 'cover', display: 'block',
          }} />
        ) : (
          <div style={{ position: 'absolute', inset: 0,
            background: `repeating-linear-gradient(${r.angle || 35}deg, rgba(255,255,255,0.06) 0 12px, transparent 12px 24px)` }} />
        )}
        {/* meta pip top-right — active effort (hidden when unknown) */}
        {(() => {
          const eff = window.LCDomain && window.LCDomain.effortInfo(r);
          if (!eff || !eff.known) return null;
          return (
            <div style={{ position: 'absolute', top: 12, right: 12 }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                padding: '4px 8px', borderRadius: 999,
                background: 'rgba(12,12,14,0.7)',
                backdropFilter: 'blur(6px)',
                border: '1px solid rgba(255,255,255,0.12)',
                fontFamily: 'Bricolage Grotesque', fontSize: 9, fontWeight: 600,
                letterSpacing: '0.14em', textTransform: 'uppercase',
                color: 'var(--ink-2)',
              }}>
                <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                  strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.85 }}>
                  <circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" />
                </svg>
                {eff.label}
              </span>
            </div>
          );
        })()}
        {/* Bottom gradient + category */}
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
          background: 'linear-gradient(180deg, transparent 50%, rgba(0,0,0,0.55) 100%)' }} />
        <div style={{ position: 'absolute', bottom: 12, left: 14, right: 14,
          display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{
            fontFamily: 'Bricolage Grotesque', fontSize: 9, fontWeight: 600,
            letterSpacing: '0.24em', textTransform: 'uppercase',
            color: 'var(--olive)',
          }}>{r.categories[0]}</span>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <h3 style={{
          fontFamily: 'Bricolage Grotesque', fontWeight: 600,
          fontSize: size === 's' ? 16 : 19, lineHeight: 1.12,
          letterSpacing: '-0.025em',
          color: 'var(--ink)', margin: 0,
          minHeight: Math.round((size === 's' ? 16 : 19) * 1.12 * 2),
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
        }}>{m ? (
          <>{m[1]}
            <span style={{ fontFamily: 'Spectral', fontStyle: 'italic',
              fontWeight: 400, color: 'var(--olive)' }}> {m[2].trim()}.</span></>
        ) : `${r.name}.`}</h3>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10,
          fontFamily: 'Bricolage Grotesque', fontSize: 11, color: 'var(--ink-3)' }}>
          {r.rating > 0
            ? <Stars value={r.rating} size={11} />
            : <span style={{ letterSpacing: '0.12em',
                textTransform: 'uppercase' }}>unrated</span>}
          <span style={{ flex: 1, height: 1, background: 'var(--hairline-2)' }} />
          {(() => {
            const label = window.LCDomain && window.LCDomain.costPerServeLabel(r);
            return label
              ? <span style={{ fontFamily: 'var(--mono)', letterSpacing: '0.02em', color: 'var(--ink-2)' }}>
                  {label}<span style={{ color: 'var(--ink-4)' }}> /serve</span></span>
              : <span style={{ letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>no cost yet</span>;
          })()}
        </div>
      </div>
    </div>
  );
};

// Map of recipe id → real photo
const FPhotos = {
  'sichuan-chicken': FPHOTO,
};

Object.assign(window, {
  ArtboardSurface,
  FPHOTO, FPhotos,
  FWordmark, FTitle, FNav, FAvatar, FHeader, FMobileHeader, FMobileBottomNav,
  FHeroImage, FIngredients, FIngredientRow,
  FButton, FPill, FRecipeCard,
});
