// screens.jsx — Today, Folk, Schedule, Detail, Add

const makeFolkById = (folks) => (id) => folks.find((f) => f.id === id);
const SPOTLIGHT_CATEGORY_DEFAULTS = { fun: true, care: false, safety: false };

function titleCaseSpecies(key) {
  return String(key || '')
    .split(' ')
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(' ');
}

function spotlightCategoriesFrom(settings) {
  const next = { ...SPOTLIGHT_CATEGORY_DEFAULTS, ...(settings || {}) };
  if (!next.fun && !next.care && !next.safety) next.fun = true;
  return next;
}

function spotlightMetaFor(species, kind) {
  const source = (window.libraryFor && window.libraryFor(kind)) || [];
  const match = source.find((item) => item.lbl.toLowerCase() === String(species || '').toLowerCase())
             || source.find((item) => String(species || '').toLowerCase().includes(item.lbl.toLowerCase()));
  return match || {
    em: kind === 'plant' ? '•' : '•',
    tint: kind === 'plant' ? 'sage' : 'sand',
  };
}

function spotlightFactsFor(species, kind, categories) {
  const care = window.careFor && window.careFor(species, kind);
  if (!care) return [];
  const rows = [];
  if (categories.fun && care.tips?.length) rows.push(...care.tips.map((text) => ({ text, category: 'Fun fact' })));
  if (categories.care) {
    const careRows = (care.headsup ? [care.headsup] : []).concat(care.needs || []);
    rows.push(...careRows.map((text) => ({ text, category: 'Care tip' })));
  }
  if (categories.safety && care.mistakes?.length) rows.push(...care.mistakes.map((text) => ({ text, category: 'Safety note' })));
  return rows;
}

function makeSpotlightEntries(folks, source, categorySettings) {
  const categories = spotlightCategoriesFrom(categorySettings);
  const matchingHouseholdFolk = (species, kind) => (folks || []).find((folk) => (
    folk.kind === kind && String(folk.species || '').toLowerCase() === String(species || '').toLowerCase()
  ));
  const ownEntries = (folks || []).flatMap((folk) => (
    spotlightFactsFor(folk.species, folk.kind, categories).map((fact, factIndex) => ({
      ...folk,
      id: `${folk.id}-spotlight-${fact.category}-${factIndex}`,
      factText: fact.text,
      factCategory: fact.category,
      source: 'own',
      visitId: folk.id,
    }))
  ));
  const libraryEntries = Object.entries(window.SPECIES_CARE || {})
    .filter(([key]) => !key.startsWith('_'))
    .flatMap(([key, care]) => {
      const species = titleCaseSpecies(key);
      const meta = spotlightMetaFor(species, care.kind);
      const householdMatch = matchingHouseholdFolk(species, care.kind);
      return spotlightFactsFor(species, care.kind, categories).map((fact, factIndex) => ({
        id: `library-${key}-${fact.category}-${factIndex}`,
        name: 'Tendlet library',
        kind: care.kind,
        species,
        tint: meta.tint,
        emoji: meta.em,
        factText: fact.text,
        factCategory: fact.category,
        source: 'library',
        visitId: householdMatch?.id,
      }));
    });
  if (source === 'ownOnly') return ownEntries.length ? ownEntries : libraryEntries;
  if (source === 'mixed') return [...ownEntries, ...libraryEntries];
  return libraryEntries.length ? libraryEntries : ownEntries;
}

// ── TODAY ────────────────────────────────────────────────────────────────
function TodayScreen({ folks, tasks, toggleTask, openDetail, completing, plantFirst, family, userName, isDemo, onAsk, spotlightHidden, spotlightSource, spotlightCategories, awayMode, familyActivity, shopItems, onOpenShop }) {
  const folkById = makeFolkById(folks);
  const activeTasks = tasks.filter((t) => folkById(t.folkId));
  const undone = activeTasks.filter((t) => !t.done).length;
  const total = activeTasks.length;
  const visibleTasks = activeTasks.filter((t) => !t.done || (completing && completing.has(t.id)));
  const allDone = visibleTasks.length === 0;
  const lowSupplies = (shopItems || []).filter((it) => it.low);
  const supplySummary = lowSupplies.length
    ? lowSupplies.slice(0, 2).map((it) => it.item || it.name).join(' · ')
    : 'Everything looks stocked';
  const homeWarnings = window.householdWarningsFor ? window.householdWarningsFor(folks) : [];
  const warningIds = homeWarnings.map((warning) => warning.id).join('|');
  const [hiddenHomeWarnings, setHiddenHomeWarnings] = React.useState(() => new Set());
  React.useEffect(() => {
    setHiddenHomeWarnings((current) => {
      const live = new Set(homeWarnings.map((warning) => warning.id));
      const next = new Set([...current].filter((id) => live.has(id)));
      return next.size === current.size ? current : next;
    });
  }, [warningIds]);
  const visibleHomeWarnings = homeWarnings.filter((warning) => !hiddenHomeWarnings.has(warning.id));

  // Spotlight: cycles through folk
  const [spotlightIdx, setSpotlightIdx] = React.useState(0);
  const spotlightPool = React.useMemo(
    () => makeSpotlightEntries(folks, spotlightSource || 'library', spotlightCategories),
    [folks, spotlightSource, spotlightCategories]
  );
  const spotlight = spotlightPool[spotlightIdx % Math.max(1, spotlightPool.length)];
  React.useEffect(() => {
    setSpotlightIdx(0);
  }, [spotlightSource, spotlightCategories]);
  const tipText = spotlight ? (spotlight.factText || window.tipFor(spotlight.species, spotlight.kind, spotlightIdx)) : null;

  // Time-aware greeting copy
  const hr = 9; // pinned to the iPhone status time
  const greeting =
    hr < 5  ? 'Up still'    :
    hr < 11 ? 'Good morning':
    hr < 17 ? 'Hello'       :
    hr < 21 ? 'Evening'     :
              'Late evening';
  const subline =
    hr < 5  ? 'Most of the house is asleep.'             :
    hr < 11 ? 'Your folk are stirring.'                  :
    hr < 17 ? 'Quiet hours. They\'re mostly resting.'    :
    hr < 21 ? 'The house is settling. Time to wind down.':
              'Most things are asleep. A few to settle.';


  return (
    <div className="screen today fade-in">
      {/* status bar spacer */}
      <div style={{ height: 54 }} />

      {/* Away banner (only when active) */}
      {window.AwayBanner && <window.AwayBanner awayMode={awayMode} />}

      {/* top kicker — date */}
      <div className="t-kicker">
        <div className="left">
          <span className="dot"></span>
          <span>Thursday <em>·</em> May 14</span>
        </div>
      </div>

      {/* hero greeting */}
      <div className="greet">
        <h1 className="hero-h1">
          <span className="drop">{greeting.charAt(0)}</span><span>{greeting.slice(1)}</span>,<br />
          <span className="name">{userName || 'Quentin'}</span>.
        </h1>
        <div className="sub">
          <i>{subline}</i>
          {!allDone && <> &nbsp;<b>{undone}</b> small kindnesses to offer.</>}
          {allDone && <> &nbsp;All <b>{total}</b> done — sit with them a while.</>}
        </div>
      </div>

      {/* spotlight card */}
      {spotlight && !spotlightHidden && (
        <Spotlight
          folk={spotlight}
          idx={spotlightIdx}
          count={spotlightPool.length}
          onCycle={() => setSpotlightIdx((i) => (i + 1) % spotlightPool.length)}
          factCategory={spotlight.factCategory}
          source={spotlight.source}
          onVisit={spotlight.visitId ? () => openDetail(spotlight.visitId) : undefined}
          tipText={tipText}
          variant="lesson"
        />
      )}

      {/* weather strip — moved below spotlight, smaller */}
      <div className="strip">
        <div className="chip">
          <window.I.sun size={13} sw={1.8} />
          <b>18°</b><span style={{ opacity: 0.7 }}>· sunny</span>
        </div>
        <div className="chip">
          <window.I.drop size={13} sw={1.8} />
          <span>Humidity </span><b>62%</b>
        </div>
        <div className="chip">
          <window.I.thermo size={13} sw={1.8} />
          <span>Indoor </span><b>21°</b>
        </div>
      </div>

      <TodayHomeWarningStrip
        warnings={visibleHomeWarnings}
        onOpen={(folkId) => openDetail(folkId)}
        onHide={(id) => setHiddenHomeWarnings((current) => {
          const next = new Set(current);
          next.add(id);
          return next;
        })}
      />

      {/* family activity */}
      {family && (familyActivity && familyActivity.length > 0) && (
        <div className="family">
          <div className="stack">
            {familyActivity.slice(0, 3).map((a, i) => (
              <div key={i} className={'av ' + ['sage', 'honey', 'terra'][i % 3]}>{a.who[0].toUpperCase()}</div>
            ))}
          </div>
          <div className="txt">
            <b>{familyActivity[0].who}</b> {familyActivity[0].verb}
            {familyActivity[1] && <> · <b>{familyActivity[1].who}</b> {familyActivity[1].verb}</>}
          </div>
        </div>
      )}

      {/* shop ribbon */}
      <button className="ribbon" onClick={onOpenShop}>
        <div className="ic"><window.I.shop size={18} sw={1.8} /></div>
        <div className="ttl">
          <b>{lowSupplies.length ? `${lowSupplies.length} ${lowSupplies.length === 1 ? 'item' : 'items'} running low` : 'Supplies stocked'}</b>
          <span>{supplySummary}</span>
        </div>
        <div className="arr"><window.I.back size={16} sw={1.8} style={{ transform: 'rotate(180deg)' }} /></div>
      </button>

      {/* tasks */}
      <window.SectionHeader
        kicker="Today's care"
        title="Small"
        accent="kindnesses"
        count={`${total - undone}/${total}`}
      />
      <div className="tasks">
        {allDone ? (
          <div className="all-done">
            <div className="ad-mark">
              <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M4 20c0-8 6-14 16-14 0 10-6 16-14 16-1.2 0-2 0-2 0z"/>
                <path d="M4 20c4-4 8-7 14-9"/>
              </svg>
            </div>
            <div className="ad-t h-serif">All done for today.</div>
            <div className="ad-d">{folks.length} thriving things, one good caretaker.</div>
          </div>
        ) : visibleTasks.map((t) => (
          <window.TaskRow key={t.id} task={t} folk={folkById(t.folkId)}
                          completing={completing && completing.has(t.id)}
                          onToggle={() => toggleTask(t.id)} />
        ))}
      </div>

      {/* Ask Tendlet — surface AI helper */}
      {onAsk && <window.AskButton folk={null} onOpen={() => onAsk(null)} />}
    </div>
  );
}

function TodayHomeWarningStrip({ warnings, onOpen, onHide }) {
  if (!warnings || warnings.length === 0) return null;
  const countText = warnings.length === 1 ? '1 warning' : `${warnings.length} warnings`;

  return (
    <section className="home-warnings" aria-label={`Needs attention, ${countText}`}>
      <div className="hw-head">
        <span>Needs attention</span>
        <b>{countText}</b>
      </div>
      <div className="hw-list">
        {warnings.map((warning) => {
          const isLethal = warning.severity === 'lethal';
          const WarningIcon = isLethal ? window.I.warningOctagon : window.I.warning;
          return (
            <div className={'hw-row ' + (isLethal ? 'lethal' : 'hard')} key={warning.id}>
              <button className="hw-open" type="button" onClick={() => onOpen(warning.folkId)}>
                <span className="hw-icon"><WarningIcon size={18} sw={1.8} /></span>
                <span className="hw-copy">
                  <strong>{warning.title}</strong>
                  <span>{warning.body}</span>
                </span>
                <span className="hw-chev"><window.I.back size={14} sw={1.9} style={{ transform: 'rotate(180deg)' }} /></span>
              </button>
              <button className="hw-hide" type="button" aria-label={`Hide from Today: ${warning.title}`} onClick={() => onHide(warning.id)}>
                <span aria-hidden="true">×</span>
              </button>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// ── Spotlight: rotating featured folk — lesson is the hero ──────────────
function Spotlight({ folk, idx, count, onCycle, onVisit, tipText, factCategory, source, variant = 'lesson' }) {
  const aboutWord = (folk.species || '').toLowerCase();
  const topicLabel = folk.species || 'Care';
  const categoryLabel = factCategory || 'Did you know';
  const tip = tipText || 'Tap to learn more.';
  const folio = `${String((idx % count) + 1).padStart(2, '0')} of ${String(count).padStart(2, '0')}`;
  const iconSrc = window.speciesIconSrc && window.speciesIconSrc(folk);
  const canVisit = typeof onVisit === 'function';
  const visitLabel = canVisit
    ? `Open ${source === 'library' ? folk.species : folk.name} detail`
    : `No household ${folk.species || 'folk'} detail in this demo`;
  const handleVisit = (e) => {
    e.stopPropagation();
    if (canVisit) onVisit();
  };
  const figureContent = folk.photoUrl
    ? <img className="sl-photo" src={folk.photoUrl} alt={folk.name} />
    : iconSrc
      ? <img className="sl-icon-img" src={iconSrc} alt="" />
      : <div className="sl-em">{folk.emoji}</div>;

  const ArrowBtn = ({ light }) => (
    <button className="sl-arrow" onClick={(e) => { e.stopPropagation(); onCycle(); }}
            aria-label="Next spotlight fact">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
           strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <path d="M5 12h14M13 6l6 6-6 6"/>
      </svg>
    </button>
  );

  return (
    <div className={'spotlight lesson' + (canVisit ? ' can-visit' : '')} data-tint={folk.tint || 'honey'} onClick={canVisit ? onVisit : undefined}>
      <div className="sl-bg">
        <div className="sl-grain"></div>
      </div>
      <div className="sl-kicker">
        <span className="sl-kicker-eyebrow">{categoryLabel}</span>
        <span className="sl-topic">{topicLabel}</span>
        <span className="counter">{folio}</span>
      </div>
      <div className="sl-content">
        <div className="sl-lesson">
          <span className="lq">"</span>{tip}<span className="lq">"</span>
        </div>
        <div className="sl-row">
          <div className="sl-attribution">
            <button className="sl-avatar sl-visit-target" onClick={handleVisit} disabled={!canVisit}
                    aria-label={visitLabel} title={visitLabel}>
              {folk.photoUrl
                ? <img className="sl-avatar-photo" src={folk.photoUrl} alt={folk.name} />
                : iconSrc
                  ? <img className="sl-avatar-icon" src={iconSrc} alt="" />
                  : <div className="sl-avatar-em">{folk.emoji}</div>}
            </button>
            <div className="sl-attr-text">
              <div className="sl-attr-name h-serif">{folk.name}</div>
              <div className="sl-attr-species">{folk.species}</div>
            </div>
          </div>
        </div>
      </div>
      <ArrowBtn />
      {canVisit ? (
        <button className="sl-figure sl-visit-target" onClick={handleVisit}
                aria-label={visitLabel} title={visitLabel}>{figureContent}</button>
      ) : (
        <div className="sl-figure" aria-label={visitLabel} title={visitLabel}>{figureContent}</div>
      )}
    </div>
  );
}

// ── Moment: editorial memory / wisdom / growth ─────────────────────────
function Moment({ moment, onCycle }) {
  return (
    <div className="moment" onClick={onCycle}>
      <div className="mo-mark" data-kind={moment.kind}>
        {moment.kind === 'memory'  && '✺'}
        {moment.kind === 'wisdom'  && '✿'}
        {moment.kind === 'growth'  && '✦'}
        {moment.kind === 'season'  && '☘'}
      </div>
      <div className="mo-body">
        <div className="mo-kicker">{moment.kicker}</div>
        <div className="mo-line h-serif">"{moment.line}"</div>
      </div>
    </div>
  );
}

function FolkCard({ folk, onClick }) {
  return (
    <div className={'folk-card ' + folk.kind} onClick={onClick}>
      <div className="kind-pill">{folk.kind === 'pet' ? 'Pet' : 'Plant'}</div>
      <FolkAvatar folk={folk} size="lg" />
      <div>
        <h3>{folk.name}</h3>
        <div className="species">{folk.species}{folk.breed ? ` · ${folk.breed}` : ''}</div>
      </div>
    </div>
  );
}

// ── FOLK (full grid) ─────────────────────────────────────────────────────
function FolkScreen({ folks, openDetail, plantFirst, onAdd }) {
  const ordered = plantFirst
    ? [...folks].sort((a, b) => (a.kind === 'plant' ? -1 : 1))
    : [...folks].sort((a, b) => (a.kind === 'pet' ? -1 : 1));
  const pets   = ordered.filter((f) => f.kind === 'pet');
  const plants = ordered.filter((f) => f.kind === 'plant');
  const groups = plantFirst
    ? [{ k: 'plant', label: 'Plants', list: plants }, { k: 'pet', label: 'Pets', list: pets }]
    : [{ k: 'pet', label: 'Pets', list: pets }, { k: 'plant', label: 'Plants', list: plants }];
  return (
    <div className="screen detail-screen fade-in">
      <div style={{ height: 54 }} />
      <div className="greet">
        <div className="folk-title-row">
          <div>
            <div className="date"><span className="dot"></span><span>Eight kinds of living</span></div>
            <h1><i>Your</i> folk</h1>
          </div>
          <button className="folk-add-btn" onClick={onAdd} aria-label="Add folk">
            <window.I.plus size={22} sw={2.2} />
          </button>
        </div>
        <div className="sub">Four with whiskers or fins, four with leaves. All loved.</div>
      </div>

      {groups.map((g) => (
        <React.Fragment key={g.k}>
          <window.SectionHeader
            kicker={g.k === 'pet' ? 'Animals' : 'Plants'}
            title={g.label}
            count={`${g.list.length}`}
          />
          <div className="folk-grid">
            {g.list.map((f) => <FolkCard key={f.id} folk={f} onClick={() => openDetail(f.id)} />)}
          </div>
        </React.Fragment>
      ))}
    </div>
  );
}

// ── SCHEDULE ─────────────────────────────────────────────────────────────
function ScheduleScreen({ folks, tasks, toggleTask, onUpdateTask }) {
  const folkById = makeFolkById(folks);
  const [editing, setEditing] = React.useState(null);
  const startEdit = (task) => {
    setEditing({
      id: task.id,
      time: task.time || '09:00',
      detail: task.detail || '',
      recurrence: task.recurrence?.type || 'daily',
    });
  };
  const saveEdit = () => {
    if (!editing) return;
    onUpdateTask && onUpdateTask(editing.id, {
      time: editing.time,
      detail: editing.detail,
      recurrence: { type: editing.recurrence },
    });
    setEditing(null);
  };
  return (
    <div className="screen fade-in">
      <div style={{ height: 54 }} />
      <div className="greet">
        <div className="date"><span className="dot"></span><span>This week · May 11 — 17</span></div>
        <h1>The week <i>ahead</i>.</h1>
        <div className="sub">Tap a day to focus. Long-press to reschedule.</div>
      </div>

      <div className="week-strip">
        {window.WEEK.map((d, i) => (
          <div key={i} className={'day' + (d.today ? ' today' : '')}>
            <div className="d">{d.d}</div>
            <div className="n">{d.date}</div>
            <div className="ct">{d.count} tasks</div>
          </div>
        ))}
      </div>

      <window.SectionHeader kicker="Thursday, May 14" title="Today's" accent="timeline" />

      <div className="timeline">
        {tasks.map((t) => {
          const f = folkById(t.folkId);
          const KIcon = window.I.kind[t.kind] || window.I.bowl;
          const isEditing = editing?.id === t.id;
          return (
            <div key={t.id} className={'t-row' + (t.done ? ' done' : '')}>
              <div className="t-time">{t.time}</div>
              <div className="t-dot"></div>
              <div className="t-card" onClick={() => toggleTask(t.id)}>
                <FolkAvatar folk={f} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="ttl">{t.verb}</div>
                  <div className="det">{t.detail}</div>
                </div>
                <button className="schedule-edit-btn" onClick={(e) => { e.stopPropagation(); startEdit(t); }} aria-label={`Edit ${t.verb}`}>
                  <window.I.more size={16} sw={1.8} />
                </button>
                <div style={{ color: 'var(--forest)' }}><KIcon size={18} sw={1.6} /></div>
              </div>
              {isEditing && (
                <div className="schedule-edit-panel">
                  <input type="time" value={editing.time} onChange={(e) => setEditing((p) => ({ ...p, time: e.target.value }))} />
                  <select value={editing.recurrence} onChange={(e) => setEditing((p) => ({ ...p, recurrence: e.target.value }))}>
                    <option value="daily">Daily</option>
                    <option value="weekly">Weekly</option>
                    <option value="monthly">Monthly</option>
                    <option value="once">Once</option>
                  </select>
                  <input value={editing.detail} onChange={(e) => setEditing((p) => ({ ...p, detail: e.target.value }))} placeholder="Details" />
                  <div className="schedule-edit-actions">
                    <button onClick={() => setEditing(null)}>Cancel</button>
                    <button onClick={saveEdit}>Save</button>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function detailDifficulty(care) {
  const n = Number(care?.difficulty || 3);
  if (n <= 1) return 'Easy';
  if (n === 2) return 'Easy-ish';
  if (n === 3) return 'Moderate';
  if (n === 4) return 'Advanced';
  return 'Expert';
}

function detailLightHint(care, fallback) {
  const line = (care?.needs || []).find((need) => {
    const l = String(need).toLowerCase();
    return l.includes('light') || l.includes('sun') || l.includes('shade');
  }) || fallback || 'Matched light';
  return String(line).split(/[—,·;:(]/)[0].trim();
}

function detailSafetyParts(line) {
  const [title, ...rest] = String(line || '').split(/\s+[—-]\s+/);
  return {
    title: rest.length ? title.trim() : String(line || '').trim(),
    body: rest.length ? rest.join(' — ').trim() : 'Keep this in mind during daily care.',
  };
}

function DetailFactCard({ label, value, sub, tone }) {
  return (
    <div className={'detail-fact-card' + (tone ? ` ${tone}` : '')}>
      <div className="detail-fact-label">{label}</div>
      <div className="detail-fact-value">{value || '—'}</div>
      {sub && <div className="detail-fact-sub">{sub}</div>}
    </div>
  );
}

function DetailFactsRow({ folk, care, formattedWeight, latestWeight }) {
  const isPet = folk.kind === 'pet';
  if (isPet) {
    const range = care?.weightRange;
    const weightSub = latestWeight
      ? 'latest log'
      : range?.freq
        ? `${range.freq} check`
        : 'baseline';
    return (
      <div className="detail-facts-row pet">
        <DetailFactCard label="Age" value={folk.age || '—'} sub={care?.lifespan ? `lifespan ${care.lifespan}` : null} />
        <DetailFactCard label="Weight" value={formattedWeight || '—'} sub={weightSub} />
        <DetailFactCard label={folk.mood ? 'Mood' : 'Difficulty'} value={folk.mood || detailDifficulty(care)} tone={folk.mood ? 'mood' : 'difficulty'} />
      </div>
    );
  }
  return (
    <div className="detail-facts-row plant">
      <div className="detail-facts-pair">
        <DetailFactCard label="Difficulty" value={detailDifficulty(care)} tone="difficulty" />
        <DetailFactCard label="Lifespan" value={care?.lifespan || 'varies'} />
      </div>
      <DetailFactCard label="Light" value={detailLightHint(care, folk.care)} sub={folk.care} />
    </div>
  );
}

function SafetyGroup({ title, icon, tint = 'rust', children }) {
  return (
    <div className="safety-group">
      <div className="safety-group-head">
        <span className={'safety-group-icon ' + tint}>{icon}</span>
        <span>{title}</span>
      </div>
      <div className="safety-group-body">{children}</div>
    </div>
  );
}

function DetailSafetyDisclosure({ folk, care, folks }) {
  const householdWarnings = window.householdWarningsFor ? window.householdWarningsFor(folks || []) : [];
  const urgent = householdWarnings.filter((warning) => warning.folkId === folk.id && warning.severity !== 'soft');
  const notes = (care?.mistakes || []).map((line, i) => ({ id: `mistake-${i}`, severity: 'soft', ...detailSafetyParts(line) }));
  const watchFor = folk.kind === 'pet'
    ? ['Not eating, sudden weight loss, laboured breathing, swelling, or unusual quietness.', 'Call a veterinarian or qualified local expert first for urgent symptoms.']
    : ['Yellowing, pests, sudden droop, mushy stems, or chewed leaves near pets.', 'Move questionable plants out of reach and contact a veterinarian if a pet chews them.'];
  const hasUrgent = urgent.length > 0;
  const tint = hasUrgent ? 'rust' : 'honey';
  const preview = hasUrgent
    ? urgent[0].body
    : notes[0]?.title || 'Care notes and emergency guidance for this profile.';
  const badgeText = [
    hasUrgent ? `${urgent.length} urgent` : null,
    notes.length ? `${notes.length} notes` : null,
    `${watchFor.length} watch`,
  ].filter(Boolean);

  return (
    <details className={'detail-disclosure safety ' + tint}>
      <summary>
        <span className="detail-disclosure-icon">
          {hasUrgent ? <window.I.warningOctagon size={15} sw={1.9} /> : <window.I.warning size={15} sw={1.9} />}
        </span>
        <span className="detail-disclosure-copy">
          <span className="detail-disclosure-top">
            <span className="native-detail-kicker">Safety</span>
            <span className="safety-badges">{badgeText.map((b) => <em key={b}>{b}</em>)}</span>
          </span>
          <strong>{hasUrgent ? 'Safety warning available' : 'Safety notes available'}</strong>
          <span className="detail-disclosure-preview">{preview}</span>
          <span className="detail-disclosure-hint">Show safety details</span>
        </span>
        <span className="detail-disclosure-chevron"><window.I.back size={14} sw={1.9} /></span>
      </summary>
      <div className="detail-disclosure-panel">
        {urgent.length > 0 && (
          <SafetyGroup title="Urgent warnings" icon="!" tint="rust">
            {urgent.map((warning) => (
              <div className={'safety-row ' + (warning.severity || 'hard')} key={warning.id}>
                <span><window.I.warning size={12} sw={2} /></span>
                <div><b>{warning.title}</b><p>{warning.body}</p></div>
              </div>
            ))}
          </SafetyGroup>
        )}
        {notes.length > 0 && (
          <SafetyGroup title="Safety notes" icon="i" tint="honey">
            {notes.map((note) => (
              <div className="safety-row soft" key={note.id}>
                <span><window.I.info size={12} sw={2} /></span>
                <div><b>{note.title}</b><p>{note.body}</p></div>
              </div>
            ))}
          </SafetyGroup>
        )}
        <SafetyGroup title="Watch for" icon="+" tint="rust">
          <div className="safety-action-banner">{watchFor[1]}</div>
          <div className="safety-watch-row"><span>1</span><p>{watchFor[0]}</p></div>
        </SafetyGroup>
        <SafetyGroup title="Sources / details" icon="≡" tint="forest">
          <div className="safety-source-note">
            {care?.level || 'Species-aware Tendlet library profile.'}
            {care?.lifespan ? ` Lifespan: ${care.lifespan}.` : ''}
          </div>
        </SafetyGroup>
      </div>
    </details>
  );
}

function DetailDisclosureCard({ title, count, preview, actionLabel, icon, tint = 'forest', defaultOpen = false, children }) {
  return (
    <details className={'detail-disclosure native ' + tint} open={defaultOpen}>
      <summary>
        <span className="detail-disclosure-icon">{icon}</span>
        <span className="detail-disclosure-copy">
          <span className="native-title-line">
            <strong>{title}</strong>
            {count && <em>{count}</em>}
          </span>
          {preview && <span className="detail-disclosure-preview">{preview}</span>}
          {actionLabel && <span className="detail-disclosure-hint">{actionLabel}</span>}
        </span>
        <span className="detail-disclosure-chevron"><window.I.back size={14} sw={1.9} /></span>
      </summary>
      <div className="detail-disclosure-panel">{children}</div>
    </details>
  );
}

function fmtDetailHistoryDate(iso) {
  if (!iso) return '—';
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return '—';
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

function detailHealthHistorySummary({ isPet, symptoms, journal, weightLog, meds, docs }) {
  const items = [
    ...(symptoms || []).map((entry) => ({
      date: entry.date,
      label: isPet ? 'symptom' : 'issue',
    })),
    ...(journal || []).map((entry) => ({ date: entry.date, label: 'journal' })),
  ];

  if (isPet) {
    items.push(
      ...(weightLog || []).map((entry) => ({ date: entry.date, label: 'weight log' })),
      ...(meds || []).map((entry) => ({ date: entry.start, label: 'medication' })),
      ...(docs || []).map((entry) => ({ date: entry.date, label: 'record' })),
    );
  }

  const count = items.length;
  const latest = items
    .filter((item) => item.date && !Number.isNaN(new Date(item.date).getTime()))
    .sort((a, b) => new Date(b.date) - new Date(a.date))[0];

  return {
    countText: count === 0 ? 'No history yet' : count === 1 ? '1 item' : `${count} items`,
    preview: latest ? `Latest: ${latest.label} · ${fmtDetailHistoryDate(latest.date)}` : 'No history yet',
  };
}

// ── DETAIL ───────────────────────────────────────────────────────────────
function DetailScreen({ folks, folkId, onBack, isDemo, onAsk, askWithPrompt, tasks, addTask, removeTask, setFolkPhoto,
                        waterLog, weightLog, onLogWater, onUndoWater, onLogWeight,
                        meds, docs, onAddMed, onRemoveMed, onAddDoc, onRemoveDoc,
                        journal, onAddJournal, onRemoveJournal,
                        symptoms, onAddSymptom, onRemoveSymptom }) {
  const folkById = makeFolkById(folks);
  const f = folkById(folkId);
  const fileInputRef = React.useRef(null);
  const handlePhoto = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file || !setFolkPhoto) return;
    const reader = new FileReader();
    reader.onload = (ev) => setFolkPhoto(folkId, ev.target.result);
    reader.readAsDataURL(file);
    e.target.value = '';
  };
  if (!f) return null;
  const isPet = f.kind === 'pet';
  const heroIcon = window.speciesIconSrc && window.speciesIconSrc(f);
  const care = window.careFor(f.species, f.kind);
  const latestWeight = (weightLog || []).find((entry) => Number.isFinite(Number(entry.kg)));
  const formattedWeight = latestWeight
    ? `${Number(latestWeight.kg).toFixed(Number(latestWeight.kg) >= 10 ? 1 : 2)} kg`
    : (f.weight || '');
  const folkTasks = (tasks || []).filter((t) => t.folkId === f.id).sort((a, b) => a.time.localeCompare(b.time));
  const needLines = (care?.needs || []).slice(0, 3);
  const healthSummary = detailHealthHistorySummary({ isPet, symptoms, journal, weightLog, meds, docs });
  const mainCareAction = isPet
    ? `${f.name}'s care rhythm for today.`
    : `${f.name}'s light, water, and seasonal checks.`;
  const fieldGuideLine = care?.level || (isPet ? 'Species-aware animal care profile.' : 'Species-aware plant care profile.');
  const shouldShowWeightTracker = isPet && (() => {
    const species = (f.species || '').toLowerCase();
    return !species.includes('fish') && !species.includes('snake') && !species.includes('lizard') &&
           !species.includes('turtle') && !species.includes('frog') && !species.includes('invertebrate');
  })();

  return (
    <div className="screen fade-in">
      <window.MiniNav onBack={onBack} title={isPet ? 'Pet' : 'Plant'} />

      {/* hero */}
      <div className="detail-hero" data-tint={f.tint}>
        <div className="detail-hero-avatar">
          {f.photoUrl
            ? <img className="detail-hero-photo" src={f.photoUrl} alt={f.name} />
            : heroIcon
              ? <img className="detail-hero-icon" src={heroIcon} alt="" />
              : <div className="glyph">{f.emoji}</div>}
          <button className="detail-photo-btn" onClick={() => fileInputRef.current?.click()}
                  title={f.photoUrl ? 'Change photo' : 'Add photo'} aria-label={f.photoUrl ? 'Change photo' : 'Add photo'}>
            <window.I.camera size={14} sw={1.8} />
          </button>
          {f.photoUrl && setFolkPhoto && (
            <button className="detail-photo-remove" onClick={() => setFolkPhoto(folkId, null)}
                    title="Remove photo" aria-label="Remove photo">
              <window.I.plus size={13} sw={2} style={{ transform: 'rotate(45deg)' }} />
            </button>
          )}
          <input ref={fileInputRef} type="file" accept="image/*" onChange={handlePhoto}
                 style={{ display: 'none' }} />
        </div>
        <div className="detail-hero-copy">
          <h1>{f.name}</h1>
          <div className="sub">{f.species}</div>
          {isPet && f.breed && <div className="detail-breed">{f.breed}</div>}
          {!isPet && f.latin && <div className="detail-breed scientific">{f.latin}</div>}
          <div className="detail-current">{isPet ? (f.age || fieldGuideLine) : (f.care || fieldGuideLine)}</div>
        </div>
      </div>

      <DetailSafetyDisclosure folk={f} care={care} folks={folks} />

      <DetailFactsRow folk={f} care={care} formattedWeight={formattedWeight} latestWeight={latestWeight} />

      {/* Ask Tendlet */}
      {onAsk && <window.AskButton folk={f} onOpen={() => onAsk(f)} />}

      <div className="detail-native-stack care-plan-section">
        <div className="detail-section-title">Care plan</div>
        <div className="care-plan-card">
          <div className="care-plan-card-head">
            <span><window.I.cal size={15} sw={1.9} /></span>
            <div>
              <b>{mainCareAction}</b>
              <p>{isPet ? 'Meals, checks, and reminders kept together.' : 'Water, light, and seasonal checks kept together.'}</p>
            </div>
          </div>
          <div className="care-plan-grid">
            {needLines.map((line, i) => (
              <div className="care-plan-pill" key={i}>{line}</div>
            ))}
          </div>
          <div className="native-mini-list">
            {folkTasks.slice(0, 3).map((t) => {
              const KIcon = window.I.kind[t.kind] || window.I.bell;
              return (
                <div className="native-mini-row" key={t.id}>
                  <span className="native-mini-time">{t.time}</span>
                  <KIcon size={15} sw={1.8} />
                  <b>{t.verb}</b>
                </div>
              );
            })}
          </div>
        </div>

        {!isPet && (
          <window.WaterMeter folk={f} log={waterLog} onLog={onLogWater} onUndo={onUndoWater} />
        )}

        {isPet && <RecommendedMealsFor folk={f} />}

        <RoutinesFor folk={f} tasks={tasks} addTask={addTask} removeTask={removeTask} />
      </div>

      <DetailDisclosureCard
        title="Health & history"
        count={healthSummary.countText}
        preview={healthSummary.preview}
        actionLabel="Show health & history"
        icon={<window.I.scale size={15} sw={1.9} />}
      >
        <div className="health-history-grid">
          {isPet && <div><b>{(weightLog || []).length}</b><span>weights</span></div>}
          {isPet && <div><b>{(meds || []).length}</b><span>meds</span></div>}
          {!isPet && <div><b>{(symptoms || []).length}</b><span>issues</span></div>}
          {isPet && <div><b>{(docs || []).length}</b><span>records</span></div>}
          <div><b>{(journal || []).length}</b><span>journal</span></div>
        </div>

        {shouldShowWeightTracker && (
          <window.WeightTracker
            folk={f}
            log={weightLog}
            onLog={onLogWeight}
            range={care?.weightRange || null}
          />
        )}

        {isPet && window.Medications && (
          <window.Medications folk={f} meds={meds} onAdd={onAddMed} onRemove={onRemoveMed} />
        )}

        {window.SymptomsLog && (
          <window.SymptomsLog folk={f} entries={symptoms}
                              onAdd={onAddSymptom} onRemove={onRemoveSymptom}
                              onAsk={askWithPrompt || onAsk} />
        )}

        {isPet && window.Documents && (
          <window.Documents folk={f} docs={docs} onAdd={onAddDoc} onRemove={onRemoveDoc} />
        )}

        {window.PhotoJournal && (
          <window.PhotoJournal folk={f} entries={journal}
                               onAdd={onAddJournal} onRemove={onRemoveJournal} />
        )}
      </DetailDisclosureCard>

      <DetailDisclosureCard
        title="Field guide"
        count={f.species}
        preview="Care basics, common mistakes, sources."
        actionLabel="Show field guide"
        icon={<window.I.info size={15} sw={1.9} />}
        tint="honey"
      >
        <div className="native-detail-footnote">Tendlet library profile · sources listed in the native care data.</div>
        <div className="field-guide-mini-list">
          {(care?.needs || []).slice(0, 4).map((line, i) => <span key={i}>{line}</span>)}
        </div>
        <window.MeetCard
          kind={f.kind}
          species={f.species}
          em={f.emoji}
          tint={f.tint}
          embedded
        />
      </DetailDisclosureCard>
    </div>
  );
}

function recommendedRoutineTemplates(folk, tasks) {
  if (!folk) return [];
  const s = (folk.species || '').toLowerCase();
  const existing = new Set((tasks || [])
    .filter((t) => t.folkId === folk.id)
    .map((t) => String(t.verb || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()));
  const nm = folk.name || (folk.kind === 'plant' ? 'this plant' : 'them');
  const templates = [];
  const add = (key, time, verb, detail, kind, recurrence) => {
    const norm = String(verb || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
    if (!existing.has(norm)) templates.push({ key, time, verb, detail, kind, recurrence: recurrence || { type: 'daily' } });
  };

  if (folk.kind === 'plant') {
    if (s.includes('fern') || s.includes('peace') || s.includes('orchid')) {
      add('humidity', '09:00', `Mist ${nm}`, 'humidity boost', 'mist', { type: 'every', days: 3 });
      add('water', '14:00', `Water ${nm}`, 'top inch should stay damp', 'water', { type: 'every', days: 4 });
    } else if (s.includes('cactus') || s.includes('succulent') || s.includes('palm')) {
      add('dry-check', '10:00', `Check ${nm}`, 'water only if soil is dry', 'water', { type: 'every', days: 14 });
      add('rotate', '12:00', `Rotate ${nm}`, 'quarter turn toward light', 'mist', { type: 'weekly', days: ['sun'] });
    } else {
      add('water', '12:30', `Water ${nm}`, '~200 ml, soak & drain', 'water', { type: 'weekly', days: ['tue'] });
      add('leaves', '14:00', `Wipe ${nm}'s leaves`, 'soft damp cloth', 'mist', { type: 'monthly', day: 15 });
    }
  } else if (s.includes('dog')) {
    add('walk-am', '07:30', `Morning walk with ${nm}`, '30 min', 'walk');
    add('breakfast', '08:00', `Breakfast for ${nm}`, 'kibble + fresh water', 'feed');
    add('walk-pm', '17:30', 'Evening walk', '45 min', 'walk');
  } else if (s.includes('cat')) {
    add('breakfast', '08:00', `Breakfast for ${nm}`, '40 g wet', 'feed');
    add('dinner', '19:00', `Dinner for ${nm}`, '40 g wet', 'feed');
    add('play', '21:00', `Play with ${nm}`, 'wand toy · 10 min', 'love');
  } else if (s.includes('fish') || s.includes('betta')) {
    add('feed', '18:30', `Feed ${nm}`, '3 pellets', 'feed', { type: 'every', days: 2 });
    add('temp', '09:00', 'Check water temp', '24-27°', 'water');
    add('water-change', '11:00', 'Tank partial water change', '25%, with conditioner', 'water', { type: 'weekly', days: ['sun'] });
  } else {
    add('hay', '08:00', `Refresh hay & water for ${nm}`, 'timothy + filtered', 'feed');
    add('greens', '12:30', `Fresh greens for ${nm}`, 'romaine + bell pepper', 'feed');
    add('lap', '20:30', `Lap time with ${nm}`, '10 min', 'love');
  }
  return templates.slice(0, 3);
}

function RecommendedMealsFor({ folk }) {
  const meals = folk?.kind === 'pet' && window.mealsForFolk ? window.mealsForFolk(folk, 3) : [];
  if (!meals.length) return null;
  return (
    <>
      <window.SectionHeader kicker="Meals" title="Recommended" accent="plan" count={`${meals.length}`} />
      <div className="detail-meals-card">
        <div className="detail-meals-head">
          <div className="detail-meals-icon"><window.I.forkKnife size={16} sw={1.9} /></div>
          <div>
            <b>{folk.name}'s Thursday meal plan</b>
            <span>From the same species-aware plan used on the Meals tab.</span>
          </div>
        </div>
        <div className="detail-meal-list">
          {meals.map((m) => (
            <div className="detail-meal-row" key={m.id}>
              <div>
                <b>{m.label}</b>
                <span>{m.note}</span>
              </div>
              <em>{m.amount}</em>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

// ── RoutinesFor: per-folk reminder list with add/edit/delete ────────────
function RoutinesFor({ folk, tasks, addTask, removeTask }) {
  const [adding, setAdding] = React.useState(false);
  const [newTime, setNewTime] = React.useState('09:00');
  const [newTitle, setNewTitle] = React.useState('');
  const [recType, setRecType] = React.useState('daily');
  const [recDays, setRecDays] = React.useState(['mon']);
  const [recEvery, setRecEvery] = React.useState(3);
  const [recMonthDay, setRecMonthDay] = React.useState(15);
  const [recDate, setRecDate] = React.useState('');

  if (!folk || !tasks) return null;
  const list = tasks.filter((t) => t.folkId === folk.id)
                    .sort((a, b) => a.time.localeCompare(b.time));
  const suggCount = list.filter((t) => t.source !== 'custom').length;
  const customCount = list.filter((t) => t.source === 'custom').length;
  const recommendations = recommendedRoutineTemplates(folk, tasks);

  const resetForm = () => {
    setNewTitle(''); setNewTime('09:00');
    setRecType('daily'); setRecDays(['mon']); setRecEvery(3); setRecMonthDay(15); setRecDate('');
  };

  const buildRecurrence = () => {
    if (recType === 'daily')   return { type: 'daily' };
    if (recType === 'weekly')  return { type: 'weekly', days: recDays.length ? recDays : ['mon'] };
    if (recType === 'every')   return { type: 'every',  days: Math.max(2, Math.min(365, Number(recEvery) || 2)) };
    if (recType === 'monthly') return { type: 'monthly', day: Math.max(1, Math.min(31, Number(recMonthDay) || 1)) };
    if (recType === 'once')    return { type: 'once', date: recDate || 'this week' };
    return { type: 'daily' };
  };

  const submit = () => {
    if (!newTitle.trim() || !addTask) return;
    addTask({
      id: `c-${Date.now()}`,
      time: newTime,
      folkId: folk.id,
      verb: newTitle.trim(),
      detail: 'custom reminder',
      kind: folk.kind === 'plant' ? 'water' : 'feed',
      done: false,
      source: 'custom',
      recurrence: buildRecurrence(),
    });
    resetForm();
    setAdding(false);
  };

  const toggleDay = (d) => setRecDays((arr) => arr.includes(d) ? arr.filter((x) => x !== d) : [...arr, d]);
  const DAY_LBL = { mon: 'M', tue: 'T', wed: 'W', thu: 'T', fri: 'F', sat: 'S', sun: 'S' };
  const DAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];

  return (
    <>
      <window.SectionHeader kicker="Routine" title="Daily" accent="reminders" count={`${list.length}`} />
      <div className="routine-card">
        <div className="routine-explainer">
          <div className="r-spark">✨</div>
          <div className="r-explainer-t">
            <b>Tendlet drafted {suggCount} from {folk.species} care guides.</b>
            <span>
              You've added {customCount} of your own. Tap × to remove, or add a new reminder below.
            </span>
          </div>
        </div>

        {list.map((t) => (
          <div className="routine-row" key={t.id}>
            <div className="r-time h-mono">{t.time}</div>
            <div className="r-body">
              <div className="r-title">{t.verb}</div>
              <div className="r-meta">
                <span className={'r-src ' + (t.source === 'custom' ? 'custom' : 'suggested')}>
                  {t.source === 'custom' ? 'Custom' : 'Suggested'}
                </span>
                <span className="r-rec">{window.formatRecurrence(t.recurrence)}</span>
              </div>
              {t.detail && <div className="r-detail-line">{t.detail}</div>}
            </div>
            <button className="r-del" onClick={() => removeTask && removeTask(t.id)} aria-label="Remove">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                   strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
            </button>
          </div>
        ))}

        {recommendations.length > 0 && (
          <div className="routine-recommendations">
            <div className="routine-rec-head">
              <span>Recommended routines</span>
              <em>tap to add</em>
            </div>
            {recommendations.map((r) => {
              const KIcon = window.I.kind[r.kind] || window.I.bell;
              return (
                <button key={r.key} className="routine-rec-row" onClick={() => addTask && addTask({
                  id: `rec-${folk.id}-${r.key}-${Date.now()}`,
                  time: r.time,
                  folkId: folk.id,
                  verb: r.verb,
                  detail: r.detail,
                  kind: r.kind,
                  done: false,
                  source: 'suggested',
                  recurrence: r.recurrence,
                })}>
                  <span className="native-mini-time">{r.time}</span>
                  <KIcon size={15} sw={1.8} />
                  <span className="routine-rec-copy">
                    <b>{r.verb}</b>
                    <small>{r.detail} · {window.formatRecurrence(r.recurrence)}</small>
                  </span>
                  <em>+</em>
                </button>
              );
            })}
          </div>
        )}

        {adding ? (
          <div className="r-add-form">
            <div className="r-add-fields">
              <input type="time" value={newTime} onChange={(e) => setNewTime(e.target.value)} className="r-time-input" />
              <input type="text" value={newTitle} onChange={(e) => setNewTitle(e.target.value)}
                     onKeyDown={(e) => e.key === 'Enter' && submit()}
                     placeholder={folk.kind === 'plant' ? 'e.g. Rotate toward window' : 'e.g. Brush after walk'}
                     autoFocus />
            </div>

            <div className="rec-block">
              <div className="rec-tabs">
                {[
                  { id: 'daily',   lbl: 'Daily'    },
                  { id: 'weekly',  lbl: 'Weekly'   },
                  { id: 'every',   lbl: 'Every X'  },
                  { id: 'monthly', lbl: 'Monthly'  },
                  { id: 'once',    lbl: 'Once'     },
                ].map((opt) => (
                  <button key={opt.id} type="button"
                          className={recType === opt.id ? 'on' : ''}
                          onClick={() => setRecType(opt.id)}>
                    {opt.lbl}
                  </button>
                ))}
              </div>

              {recType === 'daily' && (
                <div className="rec-help">Repeats every day at this time.</div>
              )}
              {recType === 'weekly' && (
                <div>
                  <div className="rec-help">Tap the days to repeat.</div>
                  <div className="rec-days">
                    {DAYS.map((d, i) => (
                      <button key={d} type="button"
                              className={recDays.includes(d) ? 'on' : ''}
                              onClick={() => toggleDay(d)}>
                        {DAY_LBL[d]}
                      </button>
                    ))}
                  </div>
                </div>
              )}
              {recType === 'every' && (
                <div className="rec-inline">
                  <span>Every</span>
                  <input type="number" min="2" max="365" value={recEvery}
                         onChange={(e) => setRecEvery(e.target.value)} className="rec-num-input" />
                  <span>days</span>
                </div>
              )}
              {recType === 'monthly' && (
                <div className="rec-inline">
                  <span>Day</span>
                  <input type="number" min="1" max="31" value={recMonthDay}
                         onChange={(e) => setRecMonthDay(e.target.value)} className="rec-num-input" />
                  <span>of each month</span>
                </div>
              )}
              {recType === 'once' && (
                <div className="rec-inline">
                  <span>On</span>
                  <input type="date" value={recDate}
                         onChange={(e) => setRecDate(e.target.value)} className="rec-date-input" />
                </div>
              )}
            </div>

            <div className="r-add-actions">
              <button className="r-cancel" onClick={() => { resetForm(); setAdding(false); }}>Cancel</button>
              <button className="r-save" onClick={submit} disabled={!newTitle.trim()}
                      style={{ opacity: newTitle.trim() ? 1 : 0.4 }}>
                Add reminder
              </button>
            </div>
          </div>
        ) : (
          <button className="r-add" onClick={() => setAdding(true)}>
            <span className="r-plus">+</span>
            <span>Add a custom reminder for {folk.name}</span>
          </button>
        )}
      </div>
    </>
  );
}

// ── ADD (in-app, single screen with search + custom) ─────────────────────
function AddScreen({ onBack, onSave }) {
  const [kind, setKind] = React.useState('pet');
  const [query, setQuery] = React.useState('');
  const [species, setSpecies] = React.useState(null); // { em, lbl, tint, custom }
  const [name, setName] = React.useState('');
  const [page, setPage] = React.useState(0);

  const lib = window.libraryFor(kind);
  const q = query.trim().toLowerCase();
  const filtered = q
    ? lib.filter((s) => s.lbl.toLowerCase().includes(q) || (s.aliases || '').toLowerCase().includes(q))
    : lib;
  const noMatch = q && filtered.length === 0;
  const pageSize = window.PICKER_PAGE_SIZE || 12;
  const pageCount = Math.max(1, Math.ceil(filtered.length / pageSize));
  const safePage = Math.min(page, pageCount - 1);
  const pageStart = safePage * pageSize;
  const pageItems = filtered.slice(pageStart, pageStart + pageSize);

  React.useEffect(() => {
    setPage(0);
  }, [kind, query]);

  return (
    <div className="screen fade-in">
        <window.MiniNav onBack={onBack} title="New folk" />
      <div className="add-screen">
        <h2>Welcome <i>another</i><br />living thing.</h2>
        <div className="lead">Search, or page through the full library — custom species welcome too.</div>

        <div className="kind-pills" style={{ marginTop: 18 }}>
          <button data-on={kind === 'pet' ? '1' : '0'} onClick={() => { setKind('pet'); setSpecies(null); }}>
            <window.I.paw size={14} sw={1.7} /> Animal
          </button>
          <button data-on={kind === 'plant' ? '1' : '0'} onClick={() => { setKind('plant'); setSpecies(null); }}>
            <window.I.leaf size={14} sw={1.7} /> Plant
          </button>
        </div>

        <div className="onb-search">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
               strokeWidth="1.8" strokeLinecap="round" style={{ color: 'var(--ink-3)', flexShrink: 0 }}>
            <circle cx="10.5" cy="10.5" r="6.5" /><path d="M20 20l-4.5-4.5" />
          </svg>
          <input value={query} onChange={(e) => { setQuery(e.target.value); setSpecies(null); }}
                 placeholder={kind === 'pet' ? 'Search: axolotl, ferret, parrot…' : 'Search: pothos, basil, succulent…'} />
          {query && (
            <button className="onb-clear" onClick={() => setQuery('')} aria-label="Clear">
              <window.I.plus size={14} sw={1.8} style={{ transform: 'rotate(45deg)' }} />
            </button>
          )}
        </div>

        {!species && (
          <>
            <div className="species-grid" style={{ marginTop: 14 }}>
              {pageItems.map((s) => (
                <button key={s.lbl} onClick={() => setSpecies({ ...s })}>
                  <window.SpeciesIcon folk={s} kind={kind} className="species-grid-icon" fallbackClassName="em" fallback={s.em} />
                  <span>{s.lbl}</span>
                </button>
              ))}
            </div>
            {filtered.length > pageSize && (
              <div className="species-pager">
                <button type="button" disabled={safePage === 0} onClick={() => setPage((p) => Math.max(0, p - 1))}>Prev</button>
                <span>{pageStart + 1}-{Math.min(pageStart + pageSize, filtered.length)} of {filtered.length}</span>
                <button type="button" disabled={safePage >= pageCount - 1} onClick={() => setPage((p) => Math.min(pageCount - 1, p + 1))}>Next</button>
              </div>
            )}
            {noMatch && (
              <button className="onb-custom" onClick={() => setSpecies({
                lbl: query.trim().replace(/\b\w/g, (c) => c.toUpperCase()),
                em: kind === 'pet' ? '•' : '•',
                tint: kind === 'pet' ? 'sand' : 'sage',
                custom: true,
              })}>
                <div className="onb-custom-ic">+</div>
                <div>
                  <b>Add "{query}" as a custom kind</b>
                  <span>We'll help you build a care routine</span>
                </div>
              </button>
            )}
          </>
        )}

	        {species && (
	          <div className="onb-naming-hero" style={{ marginTop: 18 }}>
	            <div className="avatar lg" data-tint={species.tint}>
	              <window.SpeciesIcon species={species} kind={kind} fallback={species.em} />
	            </div>
            <div className="onb-folk-info">
              <div className="h-mono" style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>
                {kind === 'pet' ? 'Animal' : 'Plant'}{species.custom ? ' · custom' : ''}
              </div>
              <div className="h-serif" style={{ fontSize: 24, marginTop: 2 }}>{species.lbl}</div>
            </div>
            <button className="onb-x" onClick={() => setSpecies(null)} aria-label="Change">
              <window.I.plus size={16} sw={1.8} style={{ transform: 'rotate(45deg)' }} />
            </button>
          </div>
        )}

        {species && (
          <div style={{ marginTop: 14 }}>
            <window.MeetCard
              kind={kind}
              species={species.lbl}
              iconKey={species.iconKey}
              em={species.em}
              tint={species.tint}
              custom={species.custom}
              embedded
            />
          </div>
        )}

        {species && (
          <>
            <div className="field" style={{ marginTop: 18 }}>
              <label>{kind === 'pet' ? 'Their name' : 'Plant nickname'}</label>
              <input autoFocus value={name} onChange={(e) => setName(e.target.value)}
                     placeholder={kind === 'pet' ? 'Luna, Mochi, Koda…' : 'Echo, Sprout, Fern…'} />
            </div>

            <div className="photo-slot">
              <div className="ic"><window.I.camera size={20} sw={1.7} /></div>
              <div><b style={{ color: 'var(--ink)' }}>Add a photo</b></div>
              <div style={{ fontSize: 11.5 }}>So they smile at you from the home screen.</div>
            </div>

            <button className="cta" onClick={() => onSave({ kind, species, name })}>
              Welcome {name || 'them'} to Tendlet
            </button>
          </>
        )}
      </div>
    </div>
  );
}

// ── PROFILE / YOU ────────────────────────────────────────────────────────
function ProfileScreen({ userName, folks, theme, setTheme, onSetUserName, onResetDemo, onRestartOnboarding, onClearPhotos,
                          tasks, vets, onAddVet, onRemoveVet,
                          family, activity, onInviteFamily, onRemoveFamily, onUpdateFamilyRole,
                          awayMode, onUpdateAway, onUpdateTask }) {
  const first = userName || 'Quentin';
  const pets   = (folks || []).filter((f) => f.kind === 'pet').length;
  const plants = (folks || []).filter((f) => f.kind === 'plant').length;
  const t = theme || {};
  const [remindersOn, setRemindersOn] = React.useState(true);
  const [groupReminders, setGroupReminders] = React.useState(true);
  const [profileSheet, setProfileSheet] = React.useState(null);
  const [nameDraft, setNameDraft] = React.useState(first);
  const [scheduleEdit, setScheduleEdit] = React.useState(null);
  const country = t.country || 'Belgium';
  const language = t.language || 'System';
  const fmt = (n, s) => `${n} ${n === 1 ? s : s + 's'}`;
  const update = (key, value) => setTheme && setTheme(key, value);
  const categories = spotlightCategoriesFrom(t.spotlightCategories);
  const settingRow = (title, icon, value, onClick, danger = false) => {
    const Icon = icon;
    return (
      <button className={'profile-row' + (danger ? ' danger' : '')} onClick={onClick || (() => {})}>
        <span className="profile-row-icon"><Icon size={17} sw={1.8} /></span>
        <span className="profile-row-title">{title}</span>
        {value && <span className="profile-row-value">{value}</span>}
        <window.I.back size={13} sw={1.8} style={{ transform: 'rotate(180deg)' }} />
      </button>
    );
  };
  const segmentRow = (label, options, selected, onSelect) => (
    <div className="profile-segment-row">
      <div className="profile-segment-label">{label}</div>
      <div className="profile-segment">
        {options.map((opt) => (
          <button key={opt.id} className={selected === opt.id ? 'on' : ''} onClick={() => onSelect(opt.id)}>
            {opt.label}
          </button>
        ))}
      </div>
    </div>
  );
  const toggleRow = (title, subtitle, icon, on, onToggle) => {
    const Icon = icon;
    return (
      <button className="profile-toggle-row" onClick={() => onToggle(!on)}>
        <span className="profile-row-icon"><Icon size={17} sw={1.8} /></span>
        <span className="profile-toggle-copy">
          <b>{title}</b>
          <span>{subtitle}</span>
        </span>
        <span className={'ios-switch' + (on ? ' on' : '')}><span></span></span>
      </button>
    );
  };
  const folkById = makeFolkById(folks || []);
  const fullRoute = ['schedule', 'family', 'vets', 'about'].includes(profileSheet);
  const profileSheetTitle = {
    name: 'Your name',
    country: 'Country',
    language: 'App language',
    family: 'Family',
    vets: 'Vets & emergencies',
    schedule: 'Schedule',
    about: 'About',
  }[profileSheet];
  const countryOptions = [
    { id: 'Belgium', value: '🇧🇪 Belgium' },
    { id: 'United States', value: '🇺🇸 United States' },
    { id: 'United Kingdom', value: '🇬🇧 United Kingdom' },
    { id: 'France', value: '🇫🇷 France' },
    { id: 'Netherlands', value: '🇳🇱 Netherlands' },
  ];
  const languageOptions = [
    { id: 'System', value: 'System' },
    { id: 'English', value: 'English' },
    { id: 'Nederlands', value: 'Nederlands' },
    { id: 'Français', value: 'Français' },
  ];
  const countryValue = (countryOptions.find((opt) => opt.id === country) || {}).value || country;
  const openScheduleEdit = (task) => setScheduleEdit({
    id: task.id,
    time: task.time || '09:00',
    detail: task.detail || '',
    recurrence: task.recurrence?.type || 'daily',
  });
  const saveScheduleEdit = () => {
    if (!scheduleEdit) return;
    onUpdateTask && onUpdateTask(scheduleEdit.id, {
      time: scheduleEdit.time,
      detail: scheduleEdit.detail,
      recurrence: { type: scheduleEdit.recurrence },
    });
    setScheduleEdit(null);
  };
  const profileSheetBody = profileSheet && (
    <div className="profile-local-overlay" onClick={() => setProfileSheet(null)}>
      <div className={'profile-local-sheet' + (fullRoute ? ' full' : '')} onClick={(e) => e.stopPropagation()}>
        <div className="profile-local-handle"></div>
        <div className="profile-local-head">
          <button className="mini-nav-btn" onClick={() => setProfileSheet(null)} aria-label="Close">
            <window.I.plus size={18} sw={1.8} style={{ transform: 'rotate(45deg)' }} />
          </button>
          <div className="h-mono mini-nav-title">{profileSheetTitle}</div>
          <span className="profile-local-spacer"></span>
        </div>

        {profileSheet === 'name' && (
          <div className="profile-local-content">
            <div className="field">
              <label>Your name</label>
              <input value={nameDraft} autoFocus onChange={(e) => setNameDraft(e.target.value)} placeholder="Quentin" />
            </div>
            <button className="cta" disabled={!nameDraft.trim()}
                    onClick={() => { onSetUserName && onSetUserName(nameDraft.trim()); setProfileSheet(null); }}
                    style={{ opacity: nameDraft.trim() ? 1 : 0.45 }}>
              Save name
            </button>
          </div>
        )}

        {profileSheet === 'country' && (
          <div className="profile-local-content">
            <div className="profile-sheet-list selectable">
              {countryOptions.map((opt) => (
                <button className="profile-sheet-row" key={opt.id}
                        data-on={country === opt.id ? '1' : '0'}
                        onClick={() => { update('country', opt.id); setProfileSheet(null); }}>
                  <span>{opt.value}</span>
                  {country === opt.id && <window.I.check size={16} sw={2.2} />}
                </button>
              ))}
            </div>
            <p className="profile-sheet-note">
              Tendlet uses this to surface the local emergency and poison-control context shown on Vets & emergencies.
            </p>
          </div>
        )}

        {profileSheet === 'language' && (
          <div className="profile-local-content">
            <div className="profile-sheet-list selectable">
              {languageOptions.map((opt) => (
                <button className="profile-sheet-row" key={opt.id}
                        data-on={language === opt.id ? '1' : '0'}
                        onClick={() => { update('language', opt.id); setProfileSheet(null); }}>
                  <span>{opt.value}</span>
                  {language === opt.id && <window.I.check size={16} sw={2.2} />}
                </button>
              ))}
            </div>
            <p className="profile-sheet-note">Choose the language Tendlet uses on this device.</p>
          </div>
        )}

        {profileSheet === 'schedule' && (
          <div className="profile-local-content">
            <div className="profile-sheet-list">
              {(tasks || []).slice(0, 10).map((task) => {
                const folk = folkById(task.folkId);
                const KIcon = window.I.kind[task.kind] || window.I.bell;
                return (
                  <div className="profile-sheet-row" key={task.id}>
                    <div className="profile-sheet-time">{task.time}</div>
                    {folk && <window.FolkAvatar folk={folk} />}
                    <div className="profile-sheet-copy">
                      <b>{task.verb}</b>
                      <span>{folk?.name || 'Household'} · {task.detail || window.formatRecurrence(task.recurrence)}</span>
                    </div>
                    <button className="profile-sheet-edit" onClick={() => openScheduleEdit(task)} aria-label={`Edit ${task.verb}`}>
                      <window.I.more size={16} sw={1.8} />
                    </button>
                    <KIcon size={16} sw={1.7} />
                  </div>
                );
              })}
            </div>
            {scheduleEdit && (
              <div className="profile-schedule-editor">
                <div className="profile-kicker">Edit reminder</div>
                <div className="health-form-row split">
                  <input className="health-input" type="time" value={scheduleEdit.time}
                         onChange={(e) => setScheduleEdit((p) => ({ ...p, time: e.target.value }))} />
                  <select className="health-input" value={scheduleEdit.recurrence}
                          onChange={(e) => setScheduleEdit((p) => ({ ...p, recurrence: e.target.value }))}>
                    <option value="daily">Daily</option>
                    <option value="weekly">Weekly</option>
                    <option value="monthly">Monthly</option>
                    <option value="once">Once</option>
                  </select>
                </div>
                <input className="health-input" value={scheduleEdit.detail}
                       onChange={(e) => setScheduleEdit((p) => ({ ...p, detail: e.target.value }))}
                       placeholder="Details" />
                <div className="r-add-actions">
                  <button className="r-cancel" onClick={() => setScheduleEdit(null)}>Cancel</button>
                  <button className="r-save" onClick={saveScheduleEdit}>Save changes</button>
                </div>
              </div>
            )}
          </div>
        )}

        {profileSheet === 'family' && window.FamilyPanel && (
          <div className="profile-local-content panels">
            <window.FamilyPanel
              members={family} activity={activity}
              onInvite={onInviteFamily} onRemove={onRemoveFamily}
              onUpdateRole={onUpdateFamilyRole}
            />
          </div>
        )}

        {profileSheet === 'vets' && window.VetContacts && (
          <div className="profile-local-content panels">
            <window.VetContacts contacts={vets} onAdd={onAddVet} onRemove={onRemoveVet} />
          </div>
        )}

        {profileSheet === 'about' && (
          <div className="profile-local-content">
            <div className="about-mini about-native">
              <h2>Tendlet</h2>
              <p className="about-lead">A calm home for the folk you keep.</p>
              {[
                ['What Tendlet is', 'A quiet field guide for the living things you keep — pets, plants, and the rituals that hold them. No streaks, no guilt, no scoreboards. Just the next small thing to do, and a place to remember why.'],
                ['The library', '216 care profiles, hand-illustrated and researched: 108 plants and 108 animals. Each profile ships with care notes, toxicity warnings where they matter, and routine suggestions you can take or leave.'],
                ['Meals', 'Researched weekly meal plans for the animal profiles that have them — use the template as a starting point or edit it for your household. Tendlet logs what was fed and when, without turning feeding into a streak.'],
                ['Your household', 'Share care with the people who live with you. Household records and logs sync through iCloud when available, and the household feed remembers who watered what.'],
                ['Safety & emergencies', 'For animal or plant emergencies, contact a veterinarian, poison-control service, or qualified expert first. Tendlet is not emergency care.'],
              ].map(([title, body]) => (
                <div className="about-section" key={title}>
                  <div className="profile-kicker">{title}</div>
                  <p>{body}</p>
                </div>
              ))}

              <div className="profile-kicker">Support & privacy</div>
              <div className="profile-sheet-list about-links">
                <div className="profile-sheet-row">
                  <window.I.info size={16} sw={1.8} />
                  <div className="profile-sheet-copy"><b>Support</b><span>For app help and release contact options.</span></div>
                </div>
                <div className="profile-sheet-row">
                  <window.I.share size={16} sw={1.8} />
                  <div className="profile-sheet-copy"><b>Privacy</b><span>How Tendlet handles care and household data.</span></div>
                </div>
              </div>

              <div className="profile-kicker">Credits</div>
              <div className="profile-sheet-list credits">
                <div className="profile-sheet-row"><span>Care data</span><b>veterinary + horticulture references</b></div>
                <div className="profile-sheet-row"><span>Illustrations</span><b>original Tendlet artwork</b></div>
                <div className="profile-sheet-row"><span>Built with</span><b>SwiftUI + CloudKit</b></div>
                <div className="profile-sheet-row"><span>Version</span><b>1.0</b></div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
  const profileSheetTarget = typeof document !== 'undefined' ? document.querySelector('.app-viewport') : null;
  const profileSheetPortal = profileSheetBody && profileSheetTarget && ReactDOM.createPortal(profileSheetBody, profileSheetTarget);

  return (
    <div className="screen fade-in">
      <div style={{ height: 54 }} />
      <div className="greet">
        <div className="date"><span className="dot"></span><span>You</span></div>
        <h1>Tend, <i>gently</i>.</h1>
        <div className="sub">Tending {fmt(pets, 'animal')} and {fmt(plants, 'plant')} as {first}.</div>
      </div>

      <div className="profile-stats">
        <div className="profile-kicker">Household</div>
        <div className="profile-stat-grid">
          {[
            { n: String(pets), l: 'Pets' },
            { n: String(plants), l: 'Plants' },
            { n: '6', l: 'Done today' },
          ].map((s, i) => (
            <div className="profile-stat" key={i}>
              <div className="h-serif">{s.n}</div>
              <span>{s.l}</span>
            </div>
          ))}
        </div>
      </div>

      <section className="profile-section">
        <div className="profile-kicker">Household</div>
        <div className="profile-card">
          {settingRow('Your name', window.I.user, first, () => { setNameDraft(first); setProfileSheet('name'); })}
          {settingRow('Country', window.I.globe, countryValue, () => setProfileSheet('country'))}
          {settingRow('Language', window.I.text, language, () => setProfileSheet('language'))}
          {settingRow('Family share', window.I.share, `${(family || []).length}`, () => setProfileSheet('family'))}
          {settingRow('Vets & emergencies', window.I.crossCase, `${(vets || []).length}`, () => setProfileSheet('vets'))}
        </div>
      </section>

      <section className="profile-section">
        <div className="profile-kicker">Care</div>
        <div className="profile-card">
          {settingRow('Schedule', window.I.cal, `${(tasks || []).length}`, () => setProfileSheet('schedule'))}
        </div>
      </section>

      <section className="profile-section">
        <div className="profile-kicker">Reminders</div>
        <div className="profile-card">
          {toggleRow(
            'Task reminders',
            remindersOn ? `On for ${(tasks || []).length} tasks.` : 'Tap any task to set a reminder.',
            window.I.bell,
            remindersOn,
            setRemindersOn
          )}
        </div>
      </section>

      <section className="profile-section">
        <div className="profile-kicker">Layout</div>
        <div className="profile-card">
          {segmentRow('Home shows', [
            { id: 'pets', label: 'Pets' },
            { id: 'plants', label: 'Plants' },
          ], t.homeOrder || 'pets', (id) => update('homeOrder', id))}
          {segmentRow('Density', [
            { id: 'regular', label: 'Regular' },
            { id: 'compact', label: 'Compact' },
          ], t.density || 'regular', (id) => update('density', id))}
          {toggleRow(
            'Group Today reminders',
            groupReminders ? 'One row per routine — folks of the same species share it.' : 'One row per folk, even if several share the same routine.',
            window.I.stack,
            groupReminders,
            setGroupReminders
          )}
        </div>
      </section>

      <section className="profile-section">
        <div className="profile-kicker">Did you know</div>
        <div className="profile-card">
          {toggleRow(
            '"Did you know" card',
            t.spotlightHidden ? 'Hidden on the home screen.' : 'Show a daily fact card on the home screen.',
            window.I.sun,
            !t.spotlightHidden,
            (on) => update('spotlightHidden', !on)
          )}
          {segmentRow('Spotlight pool', [
            { id: 'ownOnly', label: 'Own' },
            { id: 'mixed', label: 'Mixed' },
            { id: 'library', label: 'Library' },
          ], t.spotlightSource || 'library', (id) => update('spotlightSource', id))}
          <div className="profile-chip-grid">
            {[
              ['fun', 'Fun facts'],
              ['care', 'Care tips'],
              ['safety', 'Safety'],
            ].map(([id, label]) => (
              <button key={id} className={categories[id] ? 'on' : ''}
                      onClick={() => update('spotlightCategories', { ...categories, [id]: !categories[id] })}>
                {label}
              </button>
            ))}
          </div>
        </div>
      </section>

      <section className="profile-section">
        <div className="profile-kicker">Data</div>
        <div className="profile-card">
          {settingRow('About', window.I.info, '1.0', () => setProfileSheet('about'))}
          {settingRow('Restart onboarding', window.I.plus, '', onRestartOnboarding)}
          {settingRow('Clear photos', window.I.camera, '', onClearPhotos, true)}
          {settingRow('Reset to demo data', window.I.undo, '', onResetDemo, true)}
        </div>
      </section>

      {profileSheetPortal}
    </div>
  );
}

Object.assign(window, { TodayScreen, FolkScreen, ScheduleScreen, DetailScreen, AddScreen, ProfileScreen, FolkCard });
