// Food logging flow — search, quick-add, manual, detail

function LogScreen({ state, dispatch, palette }) {
  const [query, setQuery] = React.useState('');
  const [tab, setTab] = React.useState('search'); // search | recent | manual
  const [manualGrams, setManualGrams] = React.useState({ add: '', nat: '' });
  const [manualName, setManualName] = React.useState('');

  const recentIds = ['latte', 'apple', 'granola', 'yogurt-pl', 'blueberries', 'coke'];
  const recent = recentIds.map(id => FOOD_DB.find(f => f.id === id)).filter(Boolean);

  const results = query
    ? FOOD_DB.filter(f => f.name.toLowerCase().includes(query.toLowerCase()) ||
                          f.cat.toLowerCase().includes(query.toLowerCase()))
    : FOOD_DB;

  const tabBtn = (key, label) => (
    <button
      onClick={() => setTab(key)}
      style={{
        flex: 1, padding: '8px 0', border: 'none', background: 'transparent',
        fontFamily: 'inherit', fontSize: 13, fontWeight: 500, cursor: 'pointer',
        color: tab === key ? 'var(--text-1)' : 'var(--text-2)',
        borderBottom: `2px solid ${tab === key ? 'var(--accent)' : 'transparent'}`,
        transition: 'all 0.15s',
      }}
    >{label}</button>
  );

  return (
    <div style={{ padding: '0 0 40px' }}>
      {/* Header */}
      <div style={{
        padding: '60px 8px 0', display: 'flex', alignItems: 'center',
        justifyContent: 'space-between',
      }}>
        <button onClick={() => dispatch({ type: 'nav', screen: 'today' })} style={{
          padding: 12, background: 'transparent', border: 'none', cursor: 'pointer',
          color: 'var(--accent)', display: 'flex', alignItems: 'center', gap: 4,
          fontFamily: 'inherit', fontSize: 15,
        }}>
          {Icon.back(palette.accent)} Today
        </button>
        <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text-1)' }}>Log food</div>
        <div style={{ width: 80 }}/>
      </div>

      {/* Search */}
      <div style={{ padding: '12px 16px 0' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          background: 'var(--surface-2)', borderRadius: 12,
          padding: '10px 12px',
        }}>
          {Icon.search('var(--text-2)')}
          <input
            type="text"
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="Search foods, e.g. 'apple', 'latte'..."
            style={{
              flex: 1, border: 'none', background: 'transparent', outline: 'none',
              fontFamily: 'inherit', fontSize: 15, color: 'var(--text-1)',
            }}
          />
          {query && (
            <button onClick={() => setQuery('')} style={{
              background: 'var(--text-3)', borderRadius: 999, border: 'none',
              width: 18, height: 18, display: 'flex', alignItems: 'center',
              justifyContent: 'center', cursor: 'pointer', color: '#fff',
            }}>
              {Icon.close('#fff')}
            </button>
          )}
        </div>
      </div>

      {/* Tabs */}
      <div style={{
        display: 'flex', margin: '12px 16px 0',
        borderBottom: '1px solid var(--border)',
      }}>
        {tabBtn('search', 'Database')}
        {tabBtn('recent', 'Recent & favorites')}
        {tabBtn('manual', 'Manual entry')}
      </div>

      {/* Content */}
      {tab === 'search' && (
        <div style={{ padding: '8px 16px 0' }}>
          {!query && (
            <div style={{
              fontSize: 11, fontWeight: 600, letterSpacing: 0.5,
              color: 'var(--text-3)', textTransform: 'uppercase',
              padding: '10px 4px 6px',
            }}>All foods · {FOOD_DB.length}</div>
          )}
          {results.length === 0 && (
            <div style={{
              padding: 30, textAlign: 'center', color: 'var(--text-2)', fontSize: 13,
            }}>
              No matches. Try manual entry instead.
            </div>
          )}
          <div style={{
            background: 'var(--surface-1)', borderRadius: 16,
            border: '1px solid var(--border)', overflow: 'hidden',
          }}>
            {results.map((f, i) => (
              <FoodRow key={f.id} food={f} onClick={() => dispatch({ type: 'nav', screen: 'detail', food: f })}
                last={i === results.length - 1} palette={palette}/>
            ))}
          </div>
        </div>
      )}

      {tab === 'recent' && (
        <div style={{ padding: '8px 16px 0' }}>
          <div style={{
            fontSize: 11, fontWeight: 600, letterSpacing: 0.5,
            color: 'var(--text-3)', textTransform: 'uppercase',
            padding: '10px 4px 6px',
          }}>Recent · tap to quick-add 1 serving</div>
          <div style={{
            background: 'var(--surface-1)', borderRadius: 16,
            border: '1px solid var(--border)', overflow: 'hidden',
          }}>
            {recent.map((f, i) => (
              <div key={f.id} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 14px',
                borderTop: i === 0 ? 'none' : '1px solid var(--border)',
              }}>
                <FoodBadge cat={f.cat} palette={palette}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15, color: 'var(--text-1)', fontWeight: 500 }}>{f.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 1 }}>
                    {f.serving} · <span style={{ fontFamily: 'var(--font-mono)' }}>
                      +{f.add}g add · {f.nat}g nat
                    </span>
                  </div>
                </div>
                <button
                  onClick={() => {
                    dispatch({ type: 'quickAdd', food: f });
                  }}
                  style={{
                    padding: '7px 12px', borderRadius: 999,
                    background: 'var(--accent)', color: '#fff', border: 'none',
                    fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
                    display: 'flex', alignItems: 'center', gap: 3,
                  }}
                >
                  {Icon.plus('#fff')} Log
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {tab === 'manual' && (
        <div style={{ padding: '16px 16px 0' }}>
          <div style={{
            background: 'var(--surface-1)', borderRadius: 16,
            border: '1px solid var(--border)', padding: 16,
          }}>
            <div style={{ fontSize: 13, color: 'var(--text-2)', marginBottom: 12 }}>
              Log grams directly when you know the sugar content (from a nutrition label).
            </div>
            <div style={{ marginBottom: 14 }}>
              <label style={{ fontSize: 12, color: 'var(--text-2)', fontWeight: 500 }}>
                Description
              </label>
              <input
                value={manualName}
                onChange={e => setManualName(e.target.value)}
                placeholder="e.g. Homemade smoothie"
                style={{
                  width: '100%', marginTop: 6, padding: '10px 12px',
                  borderRadius: 10, border: '1px solid var(--border)',
                  fontFamily: 'inherit', fontSize: 15, outline: 'none',
                  background: 'var(--surface-2)', boxSizing: 'border-box',
                }}
              />
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              <ManualField label="Added sugar" value={manualGrams.add}
                onChange={v => setManualGrams({ ...manualGrams, add: v })}
                accent={palette.added}/>
              <ManualField label="Natural sugar" value={manualGrams.nat}
                onChange={v => setManualGrams({ ...manualGrams, nat: v })}
                accent={palette.natural}/>
            </div>
            <div style={{
              marginTop: 14, padding: 12, borderRadius: 10,
              background: 'var(--surface-2)', display: 'flex',
              justifyContent: 'space-between', alignItems: 'baseline',
            }}>
              <span style={{ fontSize: 12, color: 'var(--text-2)' }}>Total sugar</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 20, fontWeight: 600 }}>
                {(parseFloat(manualGrams.add || 0) + parseFloat(manualGrams.nat || 0)).toFixed(0)}g
              </span>
            </div>
            <button
              disabled={!manualName || (!manualGrams.add && !manualGrams.nat)}
              onClick={() => {
                dispatch({
                  type: 'manualAdd',
                  name: manualName,
                  add: parseFloat(manualGrams.add || 0),
                  nat: parseFloat(manualGrams.nat || 0),
                });
                setManualName(''); setManualGrams({ add: '', nat: '' });
              }}
              style={{
                width: '100%', marginTop: 14, padding: '13px 0',
                borderRadius: 12, background: 'var(--accent)', color: '#fff',
                border: 'none', fontFamily: 'inherit', fontSize: 15, fontWeight: 600,
                cursor: 'pointer', opacity: (!manualName || (!manualGrams.add && !manualGrams.nat)) ? 0.4 : 1,
              }}
            >Log entry</button>
          </div>
        </div>
      )}
    </div>
  );
}

function ManualField({ label, value, onChange, accent }) {
  return (
    <div style={{ flex: 1 }}>
      <label style={{
        fontSize: 12, color: 'var(--text-2)', fontWeight: 500,
        display: 'flex', alignItems: 'center', gap: 5,
      }}>
        <span style={{ width: 8, height: 8, borderRadius: 2, background: accent }}/>
        {label}
      </label>
      <div style={{ position: 'relative', marginTop: 6 }}>
        <input
          type="number"
          value={value}
          onChange={e => onChange(e.target.value)}
          placeholder="0"
          style={{
            width: '100%', padding: '10px 28px 10px 12px',
            borderRadius: 10, border: '1px solid var(--border)',
            fontFamily: 'var(--font-mono)', fontSize: 18, fontWeight: 600,
            outline: 'none', background: 'var(--surface-2)', boxSizing: 'border-box',
            color: 'var(--text-1)',
          }}
        />
        <span style={{
          position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
          fontSize: 13, color: 'var(--text-2)', pointerEvents: 'none',
        }}>g</span>
      </div>
    </div>
  );
}

function FoodRow({ food, onClick, last, palette }) {
  return (
    <button
      onClick={onClick}
      style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '11px 14px', width: '100%', textAlign: 'left',
        background: 'transparent', border: 'none', cursor: 'pointer',
        fontFamily: 'inherit',
        borderTop: '1px solid var(--border)',
      }}
    >
      <FoodBadge cat={food.cat} palette={palette}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, color: 'var(--text-1)', fontWeight: 500 }}>{food.name}</div>
        <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 1 }}>
          {food.serving}
        </div>
      </div>
      <div style={{ textAlign: 'right', marginRight: 8 }}>
        <div style={{
          fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600,
          color: food.add > 0 ? palette.added : 'var(--text-2)',
        }}>
          {food.add > 0 ? `+${food.add}g` : '0g'}
        </div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-3)' }}>
          {food.nat}g nat
        </div>
      </div>
      {Icon.chevron('var(--text-3)')}
    </button>
  );
}

// Detail view for a single food — confirm serving and log
function DetailScreen({ state, dispatch, palette, food }) {
  const [qty, setQty] = React.useState(1);
  const [meal, setMeal] = React.useState('Snack');

  const add = Math.round(food.add * qty);
  const nat = Math.round(food.nat * qty);
  const total = add + nat;
  const pctOfGoal = add / state.goal;
  const status = statusColor(pctOfGoal, palette);

  const meals = ['Breakfast', 'Lunch', 'Snack', 'Dinner'];

  return (
    <div style={{ padding: '0 0 40px' }}>
      {/* Header */}
      <div style={{
        padding: '60px 8px 0', display: 'flex', alignItems: 'center',
        justifyContent: 'space-between',
      }}>
        <button onClick={() => dispatch({ type: 'nav', screen: 'log' })} style={{
          padding: 12, background: 'transparent', border: 'none', cursor: 'pointer',
          color: 'var(--accent)', display: 'flex', alignItems: 'center', gap: 4,
          fontFamily: 'inherit', fontSize: 15,
        }}>
          {Icon.back(palette.accent)} Search
        </button>
        <div style={{ width: 80 }}/>
        <div style={{ width: 80 }}/>
      </div>

      {/* Food title */}
      <div style={{ padding: '12px 20px 0', display: 'flex', gap: 14, alignItems: 'center' }}>
        <FoodBadge cat={food.cat} palette={palette}/>
        <div>
          <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--text-1)', letterSpacing: -0.3 }}>
            {food.name}
          </div>
          <div style={{ fontSize: 13, color: 'var(--text-2)', marginTop: 2 }}>
            {food.cat} · {food.serving}
          </div>
        </div>
      </div>

      {/* Sugar breakdown card */}
      <div style={{
        margin: '18px 16px 0', padding: 18,
        background: 'var(--surface-1)', borderRadius: 20,
        border: '1px solid var(--border)',
      }}>
        <div style={{
          fontSize: 11, fontWeight: 600, letterSpacing: 0.5,
          color: 'var(--text-2)', textTransform: 'uppercase', marginBottom: 10,
        }}>Sugar per serving</div>

        <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginBottom: 4 }}>
          <span style={{
            fontFamily: 'var(--font-mono)', fontSize: 42, fontWeight: 600,
            color: 'var(--text-1)', letterSpacing: -1.5, lineHeight: 1,
          }}>{total}</span>
          <span style={{ fontSize: 18, color: 'var(--text-2)' }}>g total</span>
        </div>

        {/* Composition bar */}
        {total > 0 && (
          <div style={{
            height: 10, borderRadius: 5, overflow: 'hidden', display: 'flex',
            background: 'var(--surface-2)', marginTop: 12,
          }}>
            <div style={{ width: `${nat / total * 100}%`, background: palette.natural }}/>
            <div style={{ width: `${add / total * 100}%`, background: palette.added }}/>
          </div>
        )}

        <div style={{ display: 'flex', gap: 20, marginTop: 12 }}>
          <div>
            <div style={{
              fontSize: 11, color: 'var(--text-2)', letterSpacing: 0.4, textTransform: 'uppercase',
              display: 'flex', alignItems: 'center', gap: 5,
            }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: palette.added }}/>
              Added
            </div>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 22, fontWeight: 600,
              color: palette.added, marginTop: 2,
            }}>{add}g</div>
          </div>
          <div>
            <div style={{
              fontSize: 11, color: 'var(--text-2)', letterSpacing: 0.4, textTransform: 'uppercase',
              display: 'flex', alignItems: 'center', gap: 5,
            }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: palette.natural }}/>
              Natural
            </div>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 22, fontWeight: 600,
              color: palette.natural, marginTop: 2,
            }}>{nat}g</div>
          </div>
        </div>

        {add > 0 && (
          <div style={{
            marginTop: 14, padding: '10px 12px', borderRadius: 10,
            background: status + '12',
            display: 'flex', gap: 8, alignItems: 'center',
            fontSize: 12, color: 'var(--text-1)',
          }}>
            {Icon.info(status)}
            <span>This is <b style={{ color: status }}>{Math.round(pctOfGoal * 100)}%</b> of your {state.goal}g daily added sugar limit.</span>
          </div>
        )}
      </div>

      {/* Servings stepper */}
      <div style={{
        margin: '12px 16px 0', padding: '14px 18px',
        background: 'var(--surface-1)', borderRadius: 20,
        border: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text-1)' }}>Servings</div>
          <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 2 }}>
            {qty} × {food.serving}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <Stepper onClick={() => setQty(Math.max(0.5, qty - 0.5))}>–</Stepper>
          <span style={{
            fontFamily: 'var(--font-mono)', fontSize: 18, fontWeight: 600,
            minWidth: 30, textAlign: 'center',
          }}>{qty}</span>
          <Stepper onClick={() => setQty(qty + 0.5)}>+</Stepper>
        </div>
      </div>

      {/* Meal selector */}
      <div style={{ margin: '12px 16px 0' }}>
        <div style={{
          fontSize: 11, fontWeight: 600, letterSpacing: 0.5,
          color: 'var(--text-2)', textTransform: 'uppercase',
          padding: '0 4px 8px',
        }}>Meal</div>
        <div style={{ display: 'flex', gap: 6 }}>
          {meals.map(m => (
            <button key={m}
              onClick={() => setMeal(m)}
              style={{
                flex: 1, padding: '10px 0', borderRadius: 10,
                border: `1px solid ${meal === m ? palette.accent : 'var(--border)'}`,
                background: meal === m ? palette.accent + '12' : 'var(--surface-1)',
                color: meal === m ? palette.accent : 'var(--text-1)',
                fontFamily: 'inherit', fontSize: 13, fontWeight: 500, cursor: 'pointer',
              }}>{m}</button>
          ))}
        </div>
      </div>

      {/* Log button */}
      <div style={{ padding: '24px 16px 0' }}>
        <button
          onClick={() => {
            dispatch({ type: 'quickAdd', food, qty });
          }}
          style={{
            width: '100%', padding: '15px 0', borderRadius: 14,
            background: palette.accent, color: '#fff',
            border: 'none', fontFamily: 'inherit', fontSize: 16, fontWeight: 600,
            cursor: 'pointer',
            boxShadow: `0 6px 16px ${palette.accent}40`,
          }}
        >Log {qty === 1 ? 'this serving' : `${qty} servings`} · +{add}g added</button>
      </div>
    </div>
  );
}

function Stepper({ onClick, children }) {
  return (
    <button onClick={onClick} style={{
      width: 34, height: 34, borderRadius: 999,
      border: '1px solid var(--border)', background: 'var(--surface-2)',
      fontFamily: 'inherit', fontSize: 18, color: 'var(--text-1)',
      cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>{children}</button>
  );
}

window.LogScreen = LogScreen;
window.DetailScreen = DetailScreen;
