/* Shared Nutri components — calorie ring, macro bars, meal card, bottom nav, chip */

const nutriStyles = {
  card: {
    background: 'var(--surface)',
    border: '1px solid var(--border)',
    borderRadius: 22,
    boxShadow: 'var(--shadow-sm)',
  },
};

// ─────────────────────────────────────────────────────────────
// Circular calorie ring — main hero
// ─────────────────────────────────────────────────────────────
function CalorieRing({ value, goal, size = 120, stroke = 12, label = 'kcal' }) {
  const pct = Math.min(1, value / goal);
  const r = (size - stroke) / 2;
  const C = 2 * Math.PI * r;
  // Start at top, go clockwise — leave a small gap at bottom-right like reference (arc not full)
  const gap = 0.18; // 18% gap → arc fills 82% of circle
  const arcLen = C * (1 - gap);
  const dash = arcLen * pct;
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none"
          stroke="var(--ring-track)" strokeWidth={stroke} strokeLinecap="round"
          strokeDasharray={`${arcLen} ${C}`}
          strokeDashoffset={C * gap / 2}
          transform={`rotate(${gap * 180}, ${size/2}, ${size/2})`}
        />
        <circle cx={size/2} cy={size/2} r={r} fill="none"
          stroke="var(--ring-fill)" strokeWidth={stroke} strokeLinecap="round"
          strokeDasharray={`${dash} ${C}`}
          strokeDashoffset={C * gap / 2}
          transform={`rotate(${gap * 180}, ${size/2}, ${size/2})`}
        />
      </svg>
      <div style={{
        position: 'absolute', inset: 0, display: 'grid', placeItems: 'center',
        fontSize: size * 0.18, color: 'var(--text)',
      }}>
        <FlameIcon size={size * 0.3} />
      </div>
    </div>
  );
}

function FlameIcon({ size = 20, color = 'currentColor' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={color} aria-hidden="true">
      <path d="M12 2c1 3 4 4 4 8a4 4 0 0 1-1.2 2.9c.4-1.6-.1-3-1.2-3.9.3 2.4-1.4 3.1-1.4 5 0 .8.6 1.5 1.2 1.8C12.5 16.2 11 15 11 13c-1.2 1-2 2.4-2 4 0 2.8 2.2 5 5 5s5-2.2 5-5c0-5.6-5-7.4-7-15z"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Linear macro bar — used inside calorie card row
// ─────────────────────────────────────────────────────────────
function MacroBar({ value, goal, color, height = 6 }) {
  const pct = Math.max(0, Math.min(1, value / goal));
  return (
    <div style={{
      width: '100%', height, borderRadius: 999,
      background: 'var(--ring-track)', overflow: 'hidden',
    }}>
      <div style={{
        width: `${pct*100}%`, height: '100%',
        background: color, borderRadius: 999,
        transition: 'width .35s cubic-bezier(.2,.7,.2,1)',
      }}/>
    </div>
  );
}

// Mini ring (used for macros in some references)
function MacroRing({ value, goal, color, size = 44, stroke = 5 }) {
  const pct = Math.min(1, value / goal);
  const r = (size - stroke) / 2;
  const C = 2 * Math.PI * r;
  return (
    <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
      <circle cx={size/2} cy={size/2} r={r} fill="none"
        stroke="var(--ring-track)" strokeWidth={stroke} />
      <circle cx={size/2} cy={size/2} r={r} fill="none"
        stroke={color} strokeWidth={stroke} strokeLinecap="round"
        strokeDasharray={`${C*pct} ${C}`} />
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Calorie hero card — the centerpiece (matches ref 2 + 3)
// ─────────────────────────────────────────────────────────────
function CalorieHeroCard({ totals, goals, macroStyle = 'bars' }) {
  const left = Math.max(0, goals.calories - totals.calories);
  const pct = Math.min(1, totals.calories / goals.calories);

  const macros = [
    { key: 'protein', label: 'Protein', val: totals.protein_g, goal: goals.protein_g, color: 'var(--c-protein)' },
    { key: 'carbs',   label: 'Carbs',   val: totals.carbs_g,   goal: goals.carbs_g,   color: 'var(--c-carbs)' },
    { key: 'fat',     label: 'Fat',     val: totals.fat_g,     goal: goals.fat_g,     color: 'var(--c-fat)' },
  ];

  return (
    <div style={{
      ...nutriStyles.card,
      padding: 20,
      display: 'flex', flexDirection: 'column', gap: 18,
    }}>
      {/* Top row — big number left, ring right */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
        <div>
          <div style={{
            fontSize: 44, fontWeight: 600, letterSpacing: '-0.04em',
            color: 'var(--text)', lineHeight: 1,
          }}>
            {left.toLocaleString()}
          </div>
          <div style={{ marginTop: 6, fontSize: 13, color: 'var(--muted)', fontWeight: 500 }}>
            Calories left
          </div>
        </div>
        <CalorieRing value={totals.calories} goal={goals.calories} size={108} stroke={11} />
      </div>

      {/* Divider */}
      <div style={{ height: 1, background: 'var(--border)' }} />

      {/* Macros row */}
      {macroStyle === 'bars' ? (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
          {macros.map(m => (
            <div key={m.key}>
              <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--text)', letterSpacing: '-0.02em' }}>
                {Math.max(0, m.goal - m.val)}<span style={{ fontSize: 13, fontWeight: 500, color: 'var(--muted)' }}>g</span>
              </div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', marginBottom: 8, fontWeight: 500 }}>
                {m.label} left
              </div>
              <MacroBar value={m.val} goal={m.goal} color={m.color} />
            </div>
          ))}
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
          {macros.map(m => (
            <div key={m.key} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
              <div style={{ position: 'relative' }}>
                <MacroRing value={m.val} goal={m.goal} color={m.color} size={56} stroke={5}/>
                <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center',
                              fontSize: 12, fontWeight: 600, color: 'var(--text)' }}>
                  {m.val}<span style={{ color: 'var(--muted)', fontWeight: 500 }}>g</span>
                </div>
              </div>
              <div style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 500 }}>{m.label}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Day strip — 7 days, "today" highlighted (like ref 2 + 3)
// ─────────────────────────────────────────────────────────────
function DayStrip({ selected, onSelect, days = 7 }) {
  // build last `days` days ending today (today at right)
  const today = new Date();
  const list = [];
  for (let i = days - 1; i >= 0; i--) {
    const d = new Date(today); d.setDate(today.getDate() - i);
    list.push({
      iso: isoOf(d),
      day: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][d.getDay()],
      num: d.getDate(),
      isToday: i === 0,
    });
  }
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 4, padding: '0 2px' }}>
      {list.map(d => {
        const active = d.iso === selected;
        return (
          <button key={d.iso} onClick={() => onSelect(d.iso)} style={{
            flex: 1, minWidth: 0,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
            padding: '6px 0',
            background: 'transparent', border: 0,
            cursor: 'pointer',
            color: active ? 'var(--text)' : 'var(--muted)',
            fontFamily: 'inherit',
          }}>
            <div style={{
              fontSize: 11, fontWeight: 500, textTransform: 'uppercase',
              letterSpacing: '0.04em',
              color: active ? 'var(--text)' : 'var(--muted)',
            }}>
              {d.day.slice(0,3)}
            </div>
            <div style={{
              width: 32, height: 32, borderRadius: '50%',
              display: 'grid', placeItems: 'center',
              fontSize: 14, fontWeight: 600,
              background: active ? 'var(--text)' : 'transparent',
              color: active ? 'var(--bg)' : 'var(--text)',
              border: active ? 'none' : (d.isToday ? '1.5px solid var(--border-2)' : '1.5px solid transparent'),
              transition: 'background .15s ease, color .15s ease',
            }}>
              {d.num}
            </div>
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Meal card (recently logged) — image/thumb + name + macros
// ─────────────────────────────────────────────────────────────
function MealCard({ entry, compact = false, onClick }) {
  const mealColor = {
    breakfast: '#F5D77A', lunch: '#F0A67A', dinner: '#A99CE0', snack: '#9ED1C0',
  }[entry.meal] || '#D0CDB8';

  return (
    <button onClick={onClick} style={{
      ...nutriStyles.card,
      width: '100%',
      padding: 12,
      display: 'flex', alignItems: 'center', gap: 12,
      cursor: 'pointer',
      textAlign: 'left',
      font: 'inherit',
      color: 'var(--text)',
      transition: 'transform .12s ease, box-shadow .15s ease',
    }}
    onMouseDown={e=>e.currentTarget.style.transform='scale(.99)'}
    onMouseUp={e=>e.currentTarget.style.transform=''}
    onMouseLeave={e=>e.currentTarget.style.transform=''}
    >
      {/* thumbnail */}
      <FoodThumb emoji={entry.emoji} tint={mealColor} size={compact ? 44 : 56} />
      {/* body */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 14.5, fontWeight: 600, color: 'var(--text)',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          letterSpacing: '-0.005em',
        }}>
          {entry.name}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 3, fontSize: 12, color: 'var(--muted)', fontWeight: 500 }}>
          <FlameIcon size={11} />
          <span style={{ color: 'var(--text-2)', fontWeight: 600 }}>{entry.calories}</span>
          <span>cal</span>
          <span style={{ opacity: .4, margin: '0 4px' }}>·</span>
          <span>{NUTRI_MEAL_LABEL[entry.meal]}</span>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
          <MacroPill icon="P" val={entry.protein_g} color="var(--c-protein)" />
          <MacroPill icon="C" val={entry.carbs_g} color="var(--c-carbs)" />
          <MacroPill icon="F" val={entry.fat_g} color="var(--c-fat)" />
        </div>
      </div>
      <ChevronRight />
    </button>
  );
}

function FoodThumb({ emoji, tint, size = 56 }) {
  return (
    <div style={{
      width: size, height: size, flexShrink: 0,
      borderRadius: 14,
      background: `linear-gradient(135deg, ${tint}33 0%, ${tint}66 100%)`,
      border: '1px solid var(--border)',
      display: 'grid', placeItems: 'center',
      fontSize: size * 0.5,
      lineHeight: 1,
    }}>
      <span style={{ filter: 'saturate(1.05)' }}>{emoji}</span>
    </div>
  );
}

function MacroPill({ icon, val, color }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      fontSize: 11, fontWeight: 500, color: 'var(--text-2)',
    }}>
      <span style={{
        width: 14, height: 14, borderRadius: 4,
        background: color, color: 'white',
        display: 'inline-grid', placeItems: 'center',
        fontSize: 9, fontWeight: 700,
      }}>{icon}</span>
      {val}g
    </div>
  );
}

function ChevronRight({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
         stroke="var(--muted-2)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="9 6 15 12 9 18" />
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Bottom nav
// ─────────────────────────────────────────────────────────────
function BottomNav({ active, onChange, onAdd }) {
  const items = [
    { id: 'home',     label: 'Today',    icon: HomeIcon },
    { id: 'calendar', label: 'Calendar', icon: CalendarIcon },
    { id: 'add',      label: 'Add',      icon: PlusIcon, isAdd: true },
    { id: 'foods',    label: 'Foods',    icon: GridIcon },
    { id: 'progress', label: 'Progress', icon: ChartIcon },
  ];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '10px 18px 8px',
      gap: 4,
    }}>
      {items.map(it => {
        const Active = active === it.id;
        if (it.isAdd) {
          return (
            <button key={it.id} onClick={onAdd} aria-label="Add food" style={{
              width: 54, height: 54, borderRadius: '50%',
              border: 0, background: 'var(--text)', color: 'var(--bg)',
              display: 'grid', placeItems: 'center',
              cursor: 'pointer',
              boxShadow: '0 8px 22px -6px rgba(20,20,15,0.35), 0 0 0 4px var(--surface)',
              transform: 'translateY(-10px)',
            }}>
              <it.icon size={22} />
            </button>
          );
        }
        return (
          <button key={it.id} onClick={() => onChange(it.id)} style={{
            flex: 1, minWidth: 0,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            padding: '6px 0',
            background: 'transparent', border: 0, cursor: 'pointer',
            color: Active ? 'var(--text)' : 'var(--muted)',
            fontFamily: 'inherit',
          }}>
            <it.icon size={20} />
            <span style={{ fontSize: 10.5, fontWeight: 500 }}>{it.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Icons (line, 24 / 1.8)
// ─────────────────────────────────────────────────────────────
function Icon({ children, size = 20 }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
    stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">{children}</svg>;
}
const HomeIcon = ({size}) => <Icon size={size}><path d="M3 11l9-8 9 8v9a2 2 0 0 1-2 2h-4v-7h-6v7H5a2 2 0 0 1-2-2z"/></Icon>;
const CalendarIcon = ({size}) => <Icon size={size}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4"/></Icon>;
const PlusIcon = ({size}) => <Icon size={size}><path d="M12 5v14M5 12h14"/></Icon>;
const GridIcon = ({size}) => <Icon size={size}><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></Icon>;
const ChartIcon = ({size}) => <Icon size={size}><path d="M3 3v18h18"/><path d="M7 14l4-4 4 4 5-6"/></Icon>;
const SearchIcon = ({size}) => <Icon size={size}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></Icon>;
const BackIcon = ({size}) => <Icon size={size}><path d="M19 12H5M12 19l-7-7 7-7"/></Icon>;
const CameraIcon = ({size}) => <Icon size={size}><path d="M23 19V8a2 2 0 0 0-2-2h-3l-2-3H8L6 6H3a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h18a2 2 0 0 0 2-2z"/><circle cx="12" cy="13" r="4"/></Icon>;
const BarcodeIcon = ({size}) => <Icon size={size}><path d="M3 5v14M7 5v14M11 5v14M13 5v14M17 5v14M21 5v14"/></Icon>;
const EditIcon = ({size}) => <Icon size={size}><path d="M12 20h9M16.5 3.5a2.12 2.12 0 1 1 3 3L7 19l-4 1 1-4z"/></Icon>;
const SettingsIcon = ({size}) => <Icon size={size}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.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 1 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 1 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 1 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 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></Icon>;
const CheckIcon = ({size}) => <Icon size={size}><polyline points="20 6 9 17 4 12"/></Icon>;
const XIcon = ({size}) => <Icon size={size}><path d="M18 6L6 18M6 6l12 12"/></Icon>;
const TrendUpIcon = ({size}) => <Icon size={size}><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></Icon>;
const FireIcon = FlameIcon;

Object.assign(window, {
  nutriStyles, CalorieRing, MacroBar, MacroRing, CalorieHeroCard, DayStrip,
  MealCard, FoodThumb, MacroPill, ChevronRight, BottomNav,
  HomeIcon, CalendarIcon, PlusIcon, GridIcon, ChartIcon, SearchIcon, BackIcon,
  CameraIcon, BarcodeIcon, EditIcon, SettingsIcon, CheckIcon, XIcon, TrendUpIcon, FlameIcon, FireIcon,
});
