// tools.jsx — actual care instruments (water meter, weight tracker, sparkline)

// ─── Helpers ─────────────────────────────────────────────────────────────
const TOOLS_NOW = new Date('2026-05-14T09:24:00');

function daysSince(dateStr) {
  if (!dateStr) return 99;
  const then = new Date(dateStr);
  return Math.max(0, Math.floor((TOOLS_NOW - then) / (1000 * 60 * 60 * 24)));
}
function daysAgoDate(n) {
  const d = new Date(TOOLS_NOW);
  d.setDate(d.getDate() - n);
  return d.toISOString();
}
function fmtDate(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

// ─── Arc — semicircular gauge ────────────────────────────────────────────
function Arc({ percent, color }) {
  // angle: from -90 (needle left, percent 0) to +90 (needle right, percent 100)
  const p = Math.max(0, Math.min(100, percent));
  const angle = -90 + (p / 100) * 180;
  const ticks = [0, 25, 50, 75, 100];
  return (
    <svg viewBox="0 0 200 122" className="arc-svg" preserveAspectRatio="xMidYMid meet">
      <defs>
        <linearGradient id="moisture-grad" x1="0%" x2="100%">
          <stop offset="0%"  stopColor="#d9a86a" />
          <stop offset="38%" stopColor="#8aa07e" />
          <stop offset="68%" stopColor="#3b5a3a" />
          <stop offset="100%" stopColor="#6f8caf" />
        </linearGradient>
      </defs>
      {/* background arc */}
      <path d="M 22 100 A 78 78 0 0 1 178 100" fill="none"
            stroke="rgba(0,0,0,0.06)" strokeWidth="14" strokeLinecap="round" />
      {/* colored arc */}
      <path d="M 22 100 A 78 78 0 0 1 178 100" fill="none"
            stroke={color || 'url(#moisture-grad)'} strokeWidth="14" strokeLinecap="round" />
      {/* tick marks */}
      {ticks.map((t) => {
        const a = (180 - (t / 100) * 180) * Math.PI / 180;
        const x1 = 100 + 86 * Math.cos(a), y1 = 100 - 86 * Math.sin(a);
        const x2 = 100 + 96 * Math.cos(a), y2 = 100 - 96 * Math.sin(a);
        return <line key={t} x1={x1} y1={y1} x2={x2} y2={y2} stroke="#5a4f42" strokeWidth="1.2" />;
      })}
      {/* needle */}
      <g transform={`translate(100 100) rotate(${angle})`} className="arc-needle">
        <line x1="0" y1="6" x2="0" y2="-72" stroke="#2b2620" strokeWidth="2.5" strokeLinecap="round" />
        <circle r="9" fill="#fbf7ea" stroke="#2b2620" strokeWidth="2" />
        <circle r="2" fill="#2b2620" />
      </g>
      {/* labels */}
      <text x="20" y="118" textAnchor="middle" className="arc-lbl">DRY</text>
      <text x="100" y="20" textAnchor="middle" className="arc-lbl">DAMP</text>
      <text x="180" y="118" textAnchor="middle" className="arc-lbl">WET</text>
    </svg>
  );
}

// ─── Sparkline — 14-day moisture cycle with watering markers ─────────────
function MoistureSparkline({ log, decayPerDay = 12 }) {
  // Walk back 14 days. At each day, compute moisture by decay from most-recent water before that day.
  const days = [];
  for (let i = 13; i >= 0; i--) {
    const ago = i;
    const lastWaterBefore = (log || []).find((w) => daysSince(w.date) >= ago);
    const dsince = lastWaterBefore ? daysSince(lastWaterBefore.date) - ago : ago + 4;
    const moisture = Math.max(0, 100 - dsince * decayPerDay);
    const watered = (log || []).some((w) => daysSince(w.date) === ago);
    days.push({ ago, moisture, watered });
  }
  const W = 280, H = 56;
  const stepX = W / (days.length - 1);
  const points = days.map((d, i) => [i * stepX, H - (d.moisture / 100) * H]);
  const path = points.map(([x, y], i) => `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${y.toFixed(1)}`).join(' ');
  return (
    <svg viewBox={`0 -4 ${W} ${H + 18}`} className="spark-svg" preserveAspectRatio="none">
      {/* baseline */}
      <line x1="0" y1={H} x2={W} y2={H} stroke="rgba(0,0,0,0.08)" strokeWidth="0.5" />
      {/* fill */}
      <path d={`${path} L ${W} ${H} L 0 ${H} Z`} fill="rgba(59,90,58,0.10)" />
      {/* line */}
      <path d={path} fill="none" stroke="var(--forest)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
      {/* watering markers */}
      {days.map((d, i) =>
        d.watered ? (
          <g key={i} transform={`translate(${i * stepX} ${H + 6})`}>
            <path d="M 0 -2 L 3 4 L -3 4 Z" fill="var(--pond)" />
          </g>
        ) : null
      )}
      {/* x labels */}
      <text x="0"   y={H + 16} className="spark-lbl">14d</text>
      <text x={W/2} y={H + 16} className="spark-lbl" textAnchor="middle">7d</text>
      <text x={W}   y={H + 16} className="spark-lbl" textAnchor="end">today</text>
    </svg>
  );
}

// ─── WaterMeter — the headline plant tool ────────────────────────────────
function WaterMeter({ folk, log, onLog, onUndo }) {
  const [showEarlier, setShowEarlier] = React.useState(false);
  const last = (log || [])[0];
  const dsince = last ? daysSince(last.date) : 8;
  const rec = waterRecommendationFor(folk, dsince);
  const daysUntil = Math.max(0, rec.cadenceDays - dsince);
  const duePhrase = daysUntil === 0 ? 'today' : daysUntil === 1 ? 'tomorrow' : `in about ${daysUntil} days`;
  const lastRelative = !last ? 'No watering logged yet'
    : dsince === 0 ? 'Today'
    : dsince === 1 ? 'Yesterday'
    : `${dsince} days ago`;
  const lastExact = last ? fmtDate(last.date) : 'Use the log button when you water.';

  const logAt = (date) => {
    onLog && onLog({ date });
    setShowEarlier(false);
  };

  return (
    <div className="tool watermeter">
      <div className="tool-hd">
        <div className="tool-lbl h-mono">Watering</div>
        <div className="tool-sub h-mono">for {folk.name}</div>
      </div>

      <div className="wm-rec-card">
        <div className="wm-rec-main">
          <div>
            <div className="wm-rec-amount h-serif">≈ {rec.amount}</div>
            <div className="wm-rec-cadence">{rec.cadence}</div>
          </div>
          <button className="wm-edit-pot" type="button">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                 strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
              <path d="M4 20L20 4M14 4l6 6M4 14l6 6"/>
            </svg>
            <span>Edit pot</span>
          </button>
        </div>
        <div className="wm-due-line">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
               strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <rect x="4" y="5" width="16" height="15" rx="2"/>
            <path d="M8 3v4M16 3v4M4 10h16"/>
          </svg>
          <span>Next due: {duePhrase}</span>
        </div>
        <div className="wm-season-row">
          <span>{rec.tier}</span>
          <em>Spring: growing season</em>
        </div>
      </div>

      <div className="wm-status-card">
        <div className="wm-status-icon">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2.8c-3.5 4.9-6 8-6 11.4A6 6 0 0012 20a6 6 0 006-5.8c0-3.4-2.5-6.5-6-11.4z"/>
          </svg>
        </div>
        <div>
          <div className="wm-status-kicker h-mono">Last watered</div>
          <div className="wm-status-title">{lastRelative}</div>
          <div className="wm-status-sub">{lastExact}</div>
        </div>
      </div>

      <div className="wm-actions">
        <button className="wm-log" onClick={() => logAt(TOOLS_NOW.toISOString())}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
               strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 3c-3.5 5-6 8-6 11.5A6 6 0 0012 20a6 6 0 006-5.5C18 11 15.5 8 12 3z"/>
          </svg>
          <span>I just watered {folk.name}</span>
        </button>
        {last && (
          <button className="wm-undo" onClick={() => onUndo && onUndo()} title="Undo last log">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                 strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
              <path d="M9 14l-4-4 4-4M5 10h10a4 4 0 010 8h-1"/>
            </svg>
          </button>
        )}
      </div>

      <button className="wm-earlier" type="button" onClick={() => setShowEarlier((v) => !v)}>
        <span>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
               strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="M3 12a9 9 0 109-9M3 4v8h8"/>
          </svg>
          {showEarlier ? 'Backdate watering' : 'Did this earlier?'}
        </span>
        <em>{showEarlier ? 'Hide' : 'Show'}</em>
      </button>

      {showEarlier && (
        <div className="wm-backdate">
          <div className="wm-backdate-head">
            <span>Log watering for</span>
            <b>recently</b>
          </div>
          <div className="wm-backdate-grid">
            <button onClick={() => logAt(daysAgoDate(1))}>Yesterday</button>
            <button onClick={() => logAt(daysAgoDate(2))}>2 days ago</button>
          </div>
        </div>
      )}

      <div className="wm-history">
        <div className="wm-h-hd">
          <span className="h-mono">Past 14 days</span>
          <span className="h-mono">▼ waterings</span>
        </div>
        <MoistureSparkline log={log} />
      </div>
    </div>
  );
}

function waterRecommendationFor(folk, dsince) {
  const species = String(folk?.species || '').toLowerCase();
  if (species.includes('maidenhair')) {
    return { amount: '80-140 ml', cadence: 'every 2-3 days', cadenceDays: 3, tier: 'Moisture-loving' };
  }
  if (species.includes('ponytail')) {
    return { amount: '120-180 ml', cadence: 'every 2 weeks', cadenceDays: 14, tier: 'Low water need' };
  }
  if (species.includes('sage')) {
    return { amount: '100-160 ml', cadence: 'about weekly', cadenceDays: 7, tier: 'Low water need' };
  }
  if (species.includes('monstera')) {
    return { amount: '180-260 ml', cadence: 'about weekly', cadenceDays: 7, tier: 'Medium water need' };
  }
  const thirsty = dsince >= 7;
  return {
    amount: thirsty ? '180-240 ml' : '120-180 ml',
    cadence: thirsty ? 'water when top soil dries' : 'about weekly',
    cadenceDays: 7,
    tier: 'Medium water need',
  };
}

// ─── WeightTracker — for pets, species-aware ─────────────────────────────
function WeightTracker({ folk, log, onLog, range }) {
  const [adding, setAdding] = React.useState(false);
  const [val, setVal] = React.useState('');
  const entries = (log || []);
  const current = entries[0];
  const prev = entries[1];
  const change = current && prev ? (current.kg - prev.kg) : 0;
  const r = range && Number.isFinite(range.lo) && Number.isFinite(range.hi) ? range : null;
  // For scale bar: span 30% below lo to 30% above hi
  const scaleLo = r ? Math.max(0, r.lo - (r.hi - r.lo) * 0.6) : 0;
  const scaleHi = r ? r.hi + (r.hi - r.lo) * 0.6 : 1;

  const W = 280, H = 50;
  let chart = null;
  if (entries.length >= 2) {
    const vals = entries.slice().reverse();
    const min = Math.min(...vals.map((e) => e.kg)) - 0.05;
    const max = Math.max(...vals.map((e) => e.kg)) + 0.05;
    const stepX = W / (vals.length - 1);
    const points = vals.map((e, i) => [
      i * stepX,
      H - ((e.kg - min) / (max - min || 1)) * H,
    ]);
    const path = points.map(([x, y], i) =>
      `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${y.toFixed(1)}`).join(' ');
    chart = (
      <svg viewBox={`0 -4 ${W} ${H + 16}`} className="spark-svg" preserveAspectRatio="none">
        <path d={`${path} L ${W} ${H} L 0 ${H} Z`} fill="rgba(201,123,90,0.10)" />
        <path d={path} fill="none" stroke="var(--terra)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
        {points.map(([x, y], i) => (
          <circle key={i} cx={x} cy={y} r="2.5" fill="var(--paper-3)" stroke="var(--terra)" strokeWidth="1.4" />
        ))}
        <text x="0" y={H + 14} className="spark-lbl">{fmtDate(vals[0].date)}</text>
        <text x={W} y={H + 14} className="spark-lbl" textAnchor="end">today</text>
      </svg>
    );
  }

  const save = () => {
    const n = parseFloat(val);
    if (!Number.isFinite(n) || n <= 0) return;
    onLog && onLog({ date: TOOLS_NOW.toISOString(), kg: n });
    setVal('');
    setAdding(false);
  };

  const inRange = r && current ? (current.kg >= r.lo && current.kg <= r.hi) : null;

  return (
    <div className="tool weighttracker">
      <div className="tool-hd">
        <div className="tool-lbl h-mono">Weight log</div>
        <div className="tool-sub h-mono">
          {folk.name} · {r?.freq === 'weekly' ? 'weigh weekly' : r?.freq === 'monthly' ? 'weigh monthly' : 'track when you can'}
        </div>
      </div>

      <div className="wt-big">
        <div className="wt-val">
          <span className="wt-num h-serif">{current ? current.kg.toFixed(2) : '—'}</span>
          <span className="wt-unit h-mono">kg</span>
        </div>
        {current && change !== 0 && (
          <div className={'wt-change ' + (change > 0 ? 'up' : 'down')}>
            {change > 0 ? '↑' : '↓'} {Math.abs(change).toFixed(2)} kg <em>vs last</em>
          </div>
        )}
        {r && current && (
          <div className="wt-range">
            <div className="wt-range-bar">
              <div className="wt-range-fill"
                   style={{
                     left:  ((r.lo - scaleLo) / (scaleHi - scaleLo) * 100) + '%',
                     width: ((r.hi - r.lo) / (scaleHi - scaleLo) * 100) + '%',
                   }} />
              <div className="wt-range-marker"
                   style={{ left: ((Math.max(scaleLo, Math.min(scaleHi, current.kg)) - scaleLo) / (scaleHi - scaleLo) * 100) + '%' }} />
            </div>
            <div className="wt-range-lbl">
              <span>{scaleLo.toFixed(2)}</span>
              <em>{inRange ? `healthy ${r.lo}–${r.hi} ${r.unit}` : `target ${r.lo}–${r.hi} ${r.unit}`}</em>
              <span>{scaleHi.toFixed(2)}</span>
            </div>
          </div>
        )}
      </div>

      {chart && (
        <div className="wt-chart">
          <div className="wt-chart-hd h-mono">
            <span>Trend · {entries.length} entries</span>
            <span>{current ? `${entries.length}w of data` : ''}</span>
          </div>
          {chart}
        </div>
      )}

      {r?.note && (
        <div className="wt-note h-serif">
          <i>"{r.note}"</i>
        </div>
      )}

      {adding ? (
        <div className="wt-form">
          <input type="number" step="0.01" min="0" autoFocus value={val}
                 onChange={(e) => setVal(e.target.value)}
                 onKeyDown={(e) => e.key === 'Enter' && save()}
                 placeholder="e.g. 1.04" />
          <span className="wt-form-unit">kg</span>
          <button className="wt-cancel" onClick={() => { setAdding(false); setVal(''); }}>Cancel</button>
          <button className="wt-save" onClick={save} disabled={!val} style={{ opacity: val ? 1 : 0.4 }}>
            Log
          </button>
        </div>
      ) : (
        <button className="wt-add" onClick={() => setAdding(true)}>
          <span className="r-plus">+</span>
          <span>Log {entries.length ? 'a new' : 'first'} weight for {folk.name}</span>
        </button>
      )}
    </div>
  );
}

Object.assign(window, { WaterMeter, WeightTracker, TOOLS_NOW, daysSince, daysAgoDate });
