const { useState, useEffect, useRef, useMemo } = React;

/* =============================================================
   Icons (inline SVGs)
============================================================= */
const Icon = {
  Check: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M5 12.5l4.5 4.5L19 7.5" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  CheckThin: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M5 12.5l4.5 4.5L19 7.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  X: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>,
  ChevronRight: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M9 6l6 6-6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  ChevronLeft: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M15 6l-6 6 6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  Clock: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.6"/><path d="M12 7v5.5l3.5 2" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>,
  Tag: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M12.5 3h6a1.5 1.5 0 011.5 1.5v6L11 19.5a1.5 1.5 0 01-2.1 0L4.5 15.1a1.5 1.5 0 010-2.1L13.5 4" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/><circle cx="16.5" cy="7.5" r="1.1" fill="currentColor"/></svg>,
  Bell: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M6 16V11a6 6 0 1112 0v5l1.5 2h-15L6 16z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/><path d="M10 21a2 2 0 004 0" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>,
  Inbox: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M3 13l2.5-7A2 2 0 017.4 5h9.2a2 2 0 011.9 1.4L21 13M3 13v5a2 2 0 002 2h14a2 2 0 002-2v-5M3 13h5l1.5 2.5h5L16 13h5" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>,
  Sparkle: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M12 4v3M12 17v3M4 12h3M17 12h3M6.5 6.5l2 2M15.5 15.5l2 2M6.5 17.5l2-2M15.5 8.5l2-2" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>,
  Heart: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M12 20s-7-4.5-7-10a4 4 0 017-2.6A4 4 0 0119 10c0 5.5-7 10-7 10z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>,
  Archive: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M3 6h18v3H3zM5 9v10a1 1 0 001 1h12a1 1 0 001-1V9M10 13h4" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round"/></svg>,
  Trash: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M5 7h14M9 7V5a1 1 0 011-1h4a1 1 0 011 1v2M7 7l1 13a1 1 0 001 1h6a1 1 0 001-1l1-13" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>,
  Share: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M12 4v12M8 7l4-4 4 4M5 14v5a1 1 0 001 1h12a1 1 0 001-1v-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  Plus: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>,
  Search: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="1.6"/><path d="M20 20l-3.5-3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>,
  Dots: (p) => <svg viewBox="0 0 24 24" fill="currentColor" {...p}><circle cx="6" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="18" cy="12" r="1.6"/></svg>,
  External: (p) => <svg viewBox="0 0 24 24" fill="none" {...p}><path d="M14 4h6v6M20 4l-9 9M10 6H5a1 1 0 00-1 1v12a1 1 0 001 1h12a1 1 0 001-1v-5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  TablyMark: (p) => (
    <svg viewBox="0 0 32 32" fill="none" {...p}>
      <path d="M7 8.5h18M9 8.5v15a2 2 0 002 2h10a2 2 0 002-2v-15M14 14h4M14 18h4" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  Reddit: () => <div className="favicon reddit">r</div>,
  Wirecutter: () => <div className="favicon wirecutter">W</div>,
  State: () => <div className="favicon state">★</div>,
  Substack: () => <div className="favicon substack">S</div>,
  Amazon: () => <div className="favicon amazon">a</div>,
};

const StatusBarIcons = ({ dark }) => (
  <span className="right">
    <svg width="17" height="11" viewBox="0 0 17 11" fill="none">
      <path d="M1 7h2v3H1zM5 5h2v5H5zM9 3h2v7H9zM13 1h2v9h-2z" fill={dark ? "#fff" : "#181715"}/>
    </svg>
    <svg width="16" height="11" viewBox="0 0 16 11" fill="none">
      <path d="M8 2.5C5.5 2.5 3.3 3.4 1.6 4.9l-.7-.7C2.7 2.5 5.2 1.5 8 1.5s5.3 1 7.1 2.7l-.7.7C12.7 3.4 10.5 2.5 8 2.5z" fill={dark ? "#fff" : "#181715"}/>
      <path d="M8 5.5c-1.7 0-3.2.6-4.4 1.6l-.7-.7C4.3 5.2 6.1 4.5 8 4.5s3.7.7 5.1 1.9l-.7.7C11.2 6.1 9.7 5.5 8 5.5z" fill={dark ? "#fff" : "#181715"}/>
      <path d="M8 8.5c-.9 0-1.7.3-2.4.9l-.7-.7C5.8 7.9 6.9 7.5 8 7.5s2.2.4 3.1 1.2l-.7.7c-.7-.6-1.5-.9-2.4-.9z" fill={dark ? "#fff" : "#181715"}/>
    </svg>
    <svg width="27" height="13" viewBox="0 0 27 13" fill="none">
      <rect x="0.5" y="0.5" width="22" height="12" rx="3" stroke={dark ? "#fff" : "#181715"} opacity="0.4" fill="none"/>
      <rect x="2" y="2" width="18" height="9" rx="1.5" fill={dark ? "#fff" : "#181715"}/>
      <path d="M24 4v5c.7-.3 1-1 1-2.5S24.7 4.3 24 4z" fill={dark ? "#fff" : "#181715"} opacity="0.4"/>
    </svg>
  </span>
);

const StatusBar = ({ dark }) => (
  <div className={`status-bar ${dark ? "dark" : ""}`}>
    <span>9:41</span>
    <StatusBarIcons dark={dark} />
  </div>
);

/* =============================================================
   Initial data
============================================================= */
const initialLoops = [
  {
    id: "stroller",
    title: "Best compact stroller for travel?",
    domain: "reddit.com",
    favicon: "reddit",
    intent: "Research",
    reason: "Compare before Portugal trip",
    age: "Just now",
    status: "Review this weekend",
    urgent: true,
    isNew: true,
  },
  {
    id: "linen",
    title: "Cultiver vs Brooklinen linen sheets",
    domain: "wirecutter.com",
    favicon: "wirecutter",
    intent: "Buy",
    reason: "Old sheets are tearing",
    age: "2d",
    status: "Saved 2 days ago",
  },
  {
    id: "passport",
    title: "Renew passport online — requirements",
    domain: "travel.state.gov",
    favicon: "state",
    intent: "Follow up",
    reason: "Need before June trip",
    age: "4d",
    status: "Saved 4 days ago",
  },
  {
    id: "founder",
    title: "Founder pricing teardown",
    domain: "substack.com",
    favicon: "substack",
    intent: "Read",
    reason: "Useful for landing page pricing",
    age: "6d",
    status: "Saved 6 days ago",
  },
  {
    id: "monitor",
    title: "4K monitor under $400 — wirecutter pick",
    domain: "wirecutter.com",
    favicon: "wirecutter",
    intent: "Buy",
    reason: "Replace old display",
    age: "1w",
    status: "Saved 1 week ago",
  },
];

/* =============================================================
   Safari screen
============================================================= */
function SafariScreen({ onShare }) {
  return (
    <div className="screen screen-enter" data-screen-label="01 Safari">
      <StatusBar />
      <div className="safari" style={{ top: 54 }}>
        <div className="safari-bar-top">
          <div className="safari-url-pill">
            <span className="aa">A<span style={{fontSize: 18}}>A</span></span>
            <svg className="lock" viewBox="0 0 11 13" fill="none"><path d="M2 6V4a3.5 3.5 0 017 0v2M1.5 6h8v6.5h-8z" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round"/></svg>
            <span className="url">reddit.com</span>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M5 12a7 7 0 1014-1.5" stroke="#888" strokeWidth="1.5" strokeLinecap="round"/><path d="M19 6v4.5h-4.5" stroke="#888" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </div>
        </div>
        <div className="safari-page">
          <div className="reddit-header">
            <div className="reddit-avatar"></div>
            <div>
              <div className="reddit-sub">r/Parenting</div>
              <div className="reddit-meta">Posted by u/atticus_walks · 3h</div>
            </div>
          </div>
          <h1 className="reddit-title">Best compact stroller for travel?</h1>
          <div className="reddit-body">
            <p>We're flying to Lisbon in three weeks with our 14-month-old and the GB Pockit we have feels like it's going to fall apart. Looking for something that:</p>
            <p>1. Folds small enough to count as a carry-on</p>
            <p>2. Has a real recline so naps on the go actually work</p>
            <p>3. Doesn't require a PhD to fold one-handed</p>
            <p>I've been comparing the Babyzen YOYO2, Bugaboo Butterfly, and Joolz Aer+. The YOYO seems to win on every list but it's also the priciest. Anyone actually traveled with all three?</p>
            <p>Bonus: pediatric travel forums seem split on the Aer+ recline angle for under-2s. Real experience welcome.</p>
          </div>
          <div className="reddit-vote-row">
            <span className="v">▲ 247</span>
            <span className="v">💬 89</span>
            <span className="v">Share</span>
            <span className="v">Save</span>
          </div>
        </div>
        <div className="safari-toolbar">
          <svg viewBox="0 0 24 24" fill="none"><path d="M15 6l-6 6 6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
          <svg viewBox="0 0 24 24" fill="none" style={{opacity: 0.35}}><path d="M9 6l6 6-6 6" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
          <button
            onClick={onShare}
            aria-label="Share"
            style={{background: "none", border: 0, padding: 4, cursor: "pointer", color: "var(--accent)"}}
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M12 4v12M8 7l4-4 4 4M5 14v5a1 1 0 001 1h12a1 1 0 001-1v-5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
          <svg viewBox="0 0 24 24" fill="none"><path d="M5 8h14M5 12h14M5 16h14" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
          <svg viewBox="0 0 24 24" fill="none"><rect x="4" y="4" width="16" height="16" rx="3" stroke="currentColor" strokeWidth="1.6"/><rect x="7" y="7" width="10" height="10" rx="1.5" stroke="currentColor" strokeWidth="1.6"/></svg>
        </div>
      </div>
      <div className="home-indicator-bg"><div className="home-indicator"/></div>
    </div>
  );
}

/* =============================================================
   iOS Share sheet overlay
============================================================= */
function ShareSheet({ onClose, onSelectTably }) {
  const apps = [
    { name: "AirDrop", cls: "airdrop", glyph: <svg viewBox="0 0 24 24" fill="none" width="28" height="28"><path d="M12 4l8 8M4 12l8-8M7 15l5-5 5 5M9 21h6" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg> },
    { name: "Messages", cls: "msg", glyph: <svg viewBox="0 0 24 24" fill="none" width="28" height="28"><path d="M4 6a2 2 0 012-2h12a2 2 0 012 2v8a2 2 0 01-2 2h-7l-4 3v-3H6a2 2 0 01-2-2V6z" fill="#fff"/></svg> },
    { name: "Mail", cls: "mail", glyph: <svg viewBox="0 0 24 24" fill="none" width="28" height="28"><path d="M3 7a2 2 0 012-2h14a2 2 0 012 2v10a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" stroke="#fff" strokeWidth="1.8"/><path d="M3 8l9 6 9-6" stroke="#fff" strokeWidth="1.8" strokeLinejoin="round"/></svg> },
    { name: "Notes", cls: "notes", glyph: <svg viewBox="0 0 24 24" fill="none" width="28" height="28"><path d="M6 4h12v16H6z" fill="currentColor"/><path d="M9 8h6M9 12h6M9 16h4" stroke="#FFE48F" strokeWidth="1.4" strokeLinecap="round"/></svg> },
    { name: "Copy", cls: "copy", glyph: <svg viewBox="0 0 24 24" fill="none" width="24" height="24"><rect x="8" y="8" width="11" height="13" rx="2" stroke="currentColor" strokeWidth="1.8"/><path d="M5 16V5a2 2 0 012-2h9" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg> },
  ];
  return (
    <div className="share-sheet-overlay" onClick={onClose}>
      <div className="share-sheet" onClick={(e) => e.stopPropagation()}>
        <div className="share-grabber"/>
        <div className="share-preview">
          <div className="share-preview-thumb">r</div>
          <div style={{minWidth: 0, flex: 1}}>
            <div className="share-preview-title" style={{whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"}}>Best compact stroller for travel?</div>
            <div className="share-preview-url">reddit.com</div>
          </div>
        </div>

        <div className="share-apps-row">
          <div className="share-app" onClick={onSelectTably}>
            <div className="share-app-icon tably">
              <Icon.TablyMark style={{width: 28, height: 28}} color="#fff" stroke="#fff"/>
            </div>
            <div className="share-app-name">Tably</div>
          </div>
          {apps.map((a) => (
            <div key={a.name} className="share-app" onClick={onClose}>
              <div className={`share-app-icon ${a.cls}`}>{a.glyph}</div>
              <div className="share-app-name">{a.name}</div>
            </div>
          ))}
        </div>

        <div className="share-actions">
          <div className="share-action" onClick={onClose}>
            <span>Add to Reading List</span>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M6 4v16l6-4 6 4V4" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>
          </div>
          <div className="share-action" onClick={onClose}>
            <span>Add Bookmark</span>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M6 4v16l6-4 6 4V4z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>
          </div>
          <div className="share-action" onClick={onClose}>
            <span>Find on Page</span>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="1.6"/><path d="M20 20l-3.5-3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
          </div>
        </div>

        <div className="share-cancel" onClick={onClose}>Cancel</div>
      </div>
    </div>
  );
}

/* =============================================================
   Tably Save sheet
============================================================= */
function SaveSheet({ onCancel, onSave, onSaveOnly }) {
  const [intent, setIntent] = useState("Research");
  const [reason, setReason] = useState("Compare before Portugal trip");
  const [reminder, setReminder] = useState("This weekend");
  const intents = ["Research", "Buy", "Read", "Follow up", "Watch"];
  const reasonRef = useRef(null);

  return (
    <div className="save-sheet-overlay">
      <div className="save-sheet" onClick={(e) => e.stopPropagation()}>
        <div className="save-grabber"/>
        <div className="save-header">
          <div className="l" onClick={onCancel}>Cancel</div>
          <div className="c">Save to Tably</div>
          <div className="r"></div>
        </div>

        <div className="save-tab-card">
          <div className="save-tab-thumb">r</div>
          <div style={{minWidth: 0}}>
            <div className="save-tab-title">Best compact stroller for travel?</div>
            <div className="save-tab-url">reddit.com · r/Parenting</div>
          </div>
        </div>

        <div className="save-section-label">Why I kept this</div>
        <textarea
          ref={reasonRef}
          className="save-reason"
          rows={1}
          placeholder="A line for future you — what mattered about this?"
          value={reason}
          onChange={(e) => setReason(e.target.value)}
        />

        <div className="save-section-label">Intent</div>
        <div className="intent-pills">
          {intents.map((i) => (
            <div
              key={i}
              className={`intent-pill ${intent === i ? "active" : ""}`}
              onClick={() => setIntent(i)}
            >
              {i}
            </div>
          ))}
        </div>

        <div className="save-section-label">When to revisit</div>
        <div className="save-rows">
          <div className="save-row">
            <span className="save-row-label">
              <span className="save-row-icon"><Icon.Clock/></span>
              Review
            </span>
            <span className="save-row-value">
              {reminder} · stored locally
              <Icon.ChevronRight className="arrow" width="14" height="14"/>
            </span>
          </div>
        </div>

        <div className="save-cta">
          <button className="btn btn-primary" onClick={() => onSave({ intent, reason, reminder })}>
            Save — then close tab
          </button>
          <button className="btn btn-secondary" onClick={onSaveOnly}>
            Save only
          </button>
        </div>
      </div>
    </div>
  );
}

/* =============================================================
   Saved confirmation
============================================================= */
function SavedScreen({ savedItem, onOpenTably, onOpenPage, onUndo }) {
  return (
    <div className="screen saved-screen screen-enter" data-screen-label="03 Saved">
      <StatusBar />
      <div className="nav">
        <button className="nav-btn" onClick={onUndo}>Undo</button>
        <span/>
        <button className="nav-btn bold" onClick={onOpenTably}>Done</button>
      </div>

      <div className="saved-hero">
        <div className="saved-check">
          <Icon.Check/>
        </div>
        <h1 className="saved-headline">Saved. You can close this tab.</h1>
        <p className="saved-sub">The reason is safe. Future-you will see it.</p>

        <div className="saved-card">
          <div className="domain-row" style={{marginBottom: 8}}>
            <Icon.Reddit/>
            <span>reddit.com</span>
            <span style={{margin: "0 4px"}}>·</span>
            <span className="chip" style={{padding: "3px 8px", fontSize: 11}}>{savedItem.intent}</span>
          </div>
          <div className="saved-card-title">Best compact stroller for travel?</div>
          <div className="saved-card-quote">"{savedItem.reason}"</div>
          <div className="saved-card-row">
            <span style={{display: "inline-flex", alignItems: "center", gap: 6, color: "var(--mute)", fontSize: 13}}>
              <Icon.Bell width="14" height="14"/>
              Review {savedItem.reminder.toLowerCase()}
            </span>
            <span style={{color: "var(--sage)", fontSize: 13, fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 4}}>
              <Icon.CheckThin width="14" height="14"/>
              Stored locally
            </span>
          </div>
        </div>

        <div className="saved-actions">
          <button className="btn btn-primary" onClick={onOpenTably}>Open Tably</button>
          <button className="btn btn-secondary" onClick={onOpenPage}>Open saved page</button>
        </div>
      </div>
      <div className="home-indicator-bg"><div className="home-indicator"/></div>
    </div>
  );
}

/* =============================================================
   Open Loops list
============================================================= */
function LoopCard({ loop, onOpen }) {
  const fav = loop.favicon === "reddit" ? <Icon.Reddit/>
    : loop.favicon === "wirecutter" ? <Icon.Wirecutter/>
    : loop.favicon === "state" ? <Icon.State/>
    : loop.favicon === "substack" ? <Icon.Substack/>
    : <Icon.Amazon/>;
  return (
    <div className="loop-card" onClick={onOpen}>
      <div className="loop-card-head">
        <div className="domain-row">
          {fav}
          <span>{loop.domain}</span>
        </div>
        <span style={{flex: 1}}/>
        <span className="chip" style={{padding: "3px 8px", fontSize: 11}}>{loop.intent}</span>
      </div>
      <h3 className="loop-card-title">{loop.title}</h3>
      <div className="loop-card-quote">"{loop.reason}"</div>
      <div className="loop-card-meta">
        <span className={`loop-card-status ${loop.urgent ? "urgent" : ""}`}>{loop.status}</span>
        <span style={{color: "var(--mute)", fontSize: 12}}>{loop.age}</span>
      </div>
    </div>
  );
}

/* =============================================================
   Loop card detail sheet
============================================================= */
function LoopDetailSheet({ loop, onClose, onOpenPage, onAction }) {
  if (!loop) return null;
  const fav = loop.favicon === "reddit" ? <Icon.Reddit/>
    : loop.favicon === "wirecutter" ? <Icon.Wirecutter/>
    : loop.favicon === "state" ? <Icon.State/>
    : loop.favicon === "substack" ? <Icon.Substack/>
    : <Icon.Amazon/>;
  return (
    <div className="detail-sheet-overlay" onClick={onClose}>
      <div className="detail-sheet" onClick={(e) => e.stopPropagation()}>
        <div className="detail-grabber"/>
        <div className="detail-header">
          <span className="title">Saved reason</span>
          <button className="close" onClick={onClose}>Done</button>
        </div>

        <div className="detail-card">
          <div className="domain-row">
            {fav}
            <span>{loop.domain}</span>
            <span style={{margin: "0 4px"}}>·</span>
            <span className="chip" style={{padding: "3px 8px", fontSize: 11}}>{loop.intent}</span>
          </div>
          <h3 className="detail-card-title">{loop.title}</h3>
          <div className="detail-card-quote">"{loop.reason}"</div>
          <div className="detail-card-meta">
            <span>{loop.status}</span>
            <span style={{color: "var(--sage)", display: "inline-flex", alignItems: "center", gap: 4, fontWeight: 500}}>
              <Icon.CheckThin width="13" height="13"/>
              Stored locally
            </span>
          </div>
        </div>

        <div className="detail-actions">
          <button className="detail-action primary" onClick={onOpenPage}>
            <span className="ico"><Icon.External/></span>
            Open saved page
            <span className="arrow"><Icon.ChevronRight width="14" height="14"/></span>
          </button>
          <button className="detail-action done" onClick={() => onAction("done")}>
            <span className="ico"><Icon.CheckThin/></span>
            Mark done
          </button>
          <button className="detail-action" onClick={() => onAction("archived")}>
            <span className="ico" style={{color: "var(--ink2)"}}><Icon.Archive/></span>
            Archive
            <span style={{marginLeft: "auto", color: "var(--mute)", fontSize: 12}}>Keeps it searchable</span>
          </button>
          <button className="detail-action danger" onClick={() => onAction("deleted")}>
            <span className="ico"><Icon.Trash/></span>
            Delete
          </button>
        </div>
      </div>
    </div>
  );
}

function LoopsScreen({ loops, onStartReview, onOpenLoop, onShowSafari }) {
  const [filter, setFilter] = useState("all");
  const filters = [
    { id: "all", label: "All", count: loops.length },
    { id: "Research", label: "Research" },
    { id: "Buy", label: "Buy" },
    { id: "Read", label: "Read" },
    { id: "Follow up", label: "Follow up" },
  ];
  const visible = useMemo(
    () => filter === "all" ? loops : loops.filter(l => l.intent === filter),
    [filter, loops]
  );
  const reviewable = loops.filter(l => l.age !== "Just now").slice(0, 5).length;

  return (
    <div className="screen screen-enter" data-screen-label="04 Open Loops">
      <StatusBar />
      <div className="nav">
        <span className="nav-btn" style={{color: "var(--mute)", cursor: "default"}}>
          <Icon.Search width="22" height="22"/>
        </span>
        <span/>
        <span className="nav-btn" onClick={onShowSafari} style={{color: "var(--accent)"}}>
          <Icon.Plus width="24" height="24"/>
        </span>
      </div>
      <div className="large-title">Open Loops</div>
      <div className="large-title-sub">{loops.length} saved reasons, waiting on you.</div>

      <div className="filter-bar">
        {filters.map((f) => (
          <button
            key={f.id}
            className={`filter-pill ${filter === f.id ? "active" : ""}`}
            onClick={() => setFilter(f.id)}
          >
            {f.label}{f.count !== undefined && <span className="count">{f.count}</span>}
          </button>
        ))}
      </div>

      <div className="screen-scroll">
        {reviewable >= 3 && (
          <div className="loop-banner" onClick={onStartReview}>
            <div className="loop-banner-ico"><Icon.Heart/></div>
            <div style={{flex: 1, minWidth: 0}}>
              <div className="loop-banner-title">Still care?</div>
              <div className="loop-banner-sub">Review {reviewable} saved tabs. Keep what matters.</div>
            </div>
            <Icon.ChevronRight className="loop-banner-arrow" width="20" height="20"/>
          </div>
        )}

        <div className="loop-section-label">Saved reasons</div>
        <div className="loop-cards">
          {visible.map((l) => (
            <LoopCard key={l.id} loop={l} onOpen={() => onOpenLoop(l)}/>
          ))}
        </div>
      </div>
      <div className="home-indicator-bg"><div className="home-indicator"/></div>
    </div>
  );
}

/* =============================================================
   Still Care review
============================================================= */
function ReviewScreen({ loops, onComplete, onExit }) {
  // Snapshot the queue once on mount so it doesn't shift as we apply changes to loops mid-review.
  const [reviewQueue] = useState(() => loops.filter(l => l.age !== "Just now").slice(0, 5));
  const [idx, setIdx] = useState(0);
  const [decisions, setDecisions] = useState([]);

  const current = reviewQueue[idx];
  const total = reviewQueue.length;

  const advance = (outcome) => {
    const next = [...decisions, { id: current.id, outcome }];
    setDecisions(next);
    if (idx + 1 >= total) {
      onComplete(next);
    } else {
      setIdx(idx + 1);
    }
  };

  if (!current) {
    useEffect(() => { onExit(); }, []);
    return null;
  }

  const fav = current.favicon === "reddit" ? <Icon.Reddit/>
    : current.favicon === "wirecutter" ? <Icon.Wirecutter/>
    : current.favicon === "state" ? <Icon.State/>
    : current.favicon === "substack" ? <Icon.Substack/>
    : <Icon.Amazon/>;

  return (
    <div className="screen review-screen screen-enter" data-screen-label="05 Still Care">
      <StatusBar />
      <div className="nav">
        <button className="nav-btn nav-back" onClick={onExit}>
          <svg width="11" height="18" viewBox="0 0 11 18" fill="none"><path d="M9 1L2 9l7 8" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
          Open Loops
        </button>
        <span className="nav-title" style={{position: "absolute", left: "50%", transform: "translateX(-50%)"}}>Still Care</span>
        <span/>
      </div>

      <div className="review-progress">
        <div className="review-progress-bar">
          <div className="review-progress-fill" style={{width: `${(idx / total) * 100}%`}}/>
        </div>
        <div className="review-progress-label">
          <span>{idx + 1} of {total}</span>
          <span>{total - idx - 1} more</span>
        </div>
      </div>

      <div className="review-body">
        <h1 className="review-prompt">Still care?</h1>
        <p className="review-prompt-sub">Keep what matters. Clear what doesn't.</p>

        <div className="review-card" key={current.id}>
          <div className="domain-row">
            {fav}
            <span>{current.domain}</span>
            <span style={{margin: "0 4px"}}>·</span>
            <span style={{color: "var(--mute)", fontSize: 13}}>Saved {current.age} ago</span>
          </div>
          <h2 className="review-card-title">{current.title}</h2>
          <div className="review-card-quote">"{current.reason}"</div>
          <div className="review-card-meta">
            <span className="chip">{current.intent}</span>
            <span className="chip outline">
              <Icon.Clock width="12" height="12"/>
              <span style={{marginLeft: 4}}>Saved {current.age}</span>
            </span>
          </div>
        </div>
      </div>

      <div className="review-actions">
        <button className="review-action keep" onClick={() => advance("kept")}>
          <Icon.Heart width="18" height="18"/>
          Keep for later
        </button>
        <button className="review-action done" onClick={() => advance("done")}>
          <Icon.CheckThin width="16" height="16"/>
          Done
        </button>
        <button className="review-action archive" onClick={() => advance("archived")}>
          <Icon.Archive width="16" height="16"/>
          Archive
        </button>
        <button className="review-action delete" onClick={() => advance("deleted")} style={{gridColumn: "1 / -1"}}>
          <Icon.Trash width="16" height="16"/>
          Delete
        </button>
      </div>
      <p className="review-tip">Archive keeps it searchable.</p>
      <div className="home-indicator-bg"><div className="home-indicator"/></div>
    </div>
  );
}

/* =============================================================
   Completion
============================================================= */
function CompleteScreen({ decisions, onBack }) {
  const counts = decisions.reduce((acc, d) => { acc[d.outcome] = (acc[d.outcome] || 0) + 1; return acc; }, {});
  return (
    <div className="screen screen-enter" data-screen-label="06 Review complete">
      <StatusBar />
      <div className="complete-screen">
        <div className="complete-ico"><Icon.Check/></div>
        <h1 className="complete-headline">Review complete.</h1>
        <p className="complete-sub">{decisions.length} reasons reviewed.</p>

        <div className="complete-stats">
          <div className="complete-stat">
            <span className="complete-stat-label"><span className="complete-stat-dot done"/>Done</span>
            <span className="complete-stat-count">{counts.done || 0}</span>
          </div>
          <div className="complete-stat">
            <span className="complete-stat-label"><span className="complete-stat-dot archived"/>Archived</span>
            <span className="complete-stat-count">{counts.archived || 0}</span>
          </div>
          <div className="complete-stat">
            <span className="complete-stat-label"><span className="complete-stat-dot deleted"/>Deleted</span>
            <span className="complete-stat-count">{counts.deleted || 0}</span>
          </div>
          <div className="complete-stat">
            <span className="complete-stat-label"><span className="complete-stat-dot kept"/>Kept for later</span>
            <span className="complete-stat-count">{counts.kept || 0}</span>
          </div>
        </div>

        <button className="btn btn-primary" onClick={onBack}>Back to Open Loops</button>
      </div>
      <div className="home-indicator-bg"><div className="home-indicator"/></div>
    </div>
  );
}

/* =============================================================
   App shell
============================================================= */
function App() {
  // screens: safari -> share -> save -> saved -> loops -> review -> complete
  const [screen, setScreen] = useState("safari");
  const [showShare, setShowShare] = useState(false);
  const [showSave, setShowSave] = useState(false);
  const [loops, setLoops] = useState(initialLoops);
  const [savedItem, setSavedItem] = useState({
    intent: "Research",
    reason: "Compare before Portugal trip",
    reminder: "This weekend",
  });
  const [decisions, setDecisions] = useState([]);
  const [activeLoop, setActiveLoop] = useState(null);

  // Demo controls
  useEffect(() => {
    const jumps = [
      ["Safari tab", () => { setShowShare(false); setShowSave(false); setScreen("safari"); }],
      ["Share sheet", () => { setShowSave(false); setScreen("safari"); setShowShare(true); }],
      ["Save sheet", () => { setShowShare(false); setScreen("safari"); setShowSave(true); }],
      ["Saved confirmation", () => { setShowShare(false); setShowSave(false); setScreen("saved"); }],
      ["Open Loops", () => { setShowShare(false); setShowSave(false); setScreen("loops"); }],
      ["Still Care review", () => { setShowShare(false); setShowSave(false); setScreen("review"); }],
      ["Review complete", () => {
        setDecisions([
          { id: "linen", outcome: "done" },
          { id: "passport", outcome: "done" },
          { id: "founder", outcome: "archived" },
          { id: "monitor", outcome: "deleted" },
          { id: "stroller", outcome: "kept" },
        ]);
        setShowShare(false); setShowSave(false); setScreen("complete");
      }],
      ["Reset prototype", () => {
        setLoops(initialLoops); setDecisions([]); setShowShare(false); setShowSave(false); setScreen("safari");
      }],
    ];
    const host = document.getElementById("demo-jumps");
    if (!host) return;
    host.innerHTML = "";
    jumps.forEach(([label, fn]) => {
      const b = document.createElement("button");
      b.textContent = label;
      b.onclick = fn;
      host.appendChild(b);
    });
  }, [screen]);

  const handleSave = (data) => {
    setSavedItem(data);
    // Update or insert the just-saved loop
    setLoops((prev) => {
      const idx = prev.findIndex(l => l.id === "stroller");
      if (idx >= 0) {
        const updated = [...prev];
        updated[idx] = {
          ...updated[idx],
          intent: data.intent,
          reason: data.reason,
          status: data.reminder === "No reminder" ? "Just saved" : `Review ${data.reminder.toLowerCase()}`,
          urgent: data.reminder !== "No reminder",
          isNew: true,
          age: "Just now",
        };
        return updated;
      }
      return prev;
    });
    setShowSave(false);
    setScreen("saved");
  };

  return (
    <div className="stage">
      <div className="phone">
        <div className="notch"/>
        <div className="phone-screen">
          {screen === "safari" && (
            <SafariScreen onShare={() => setShowShare(true)} />
          )}
          {screen === "saved" && (
            <SavedScreen
              savedItem={savedItem}
              onOpenTably={() => setScreen("loops")}
              onOpenPage={() => setScreen("safari")}
              onUndo={() => { setShowShare(false); setShowSave(false); setScreen("safari"); }}
            />
          )}
          {screen === "loops" && (
            <LoopsScreen
              loops={loops}
              onStartReview={() => setScreen("review")}
              onOpenLoop={(l) => setActiveLoop(l)}
              onShowSafari={() => setScreen("safari")}
            />
          )}
          {screen === "review" && (
            <ReviewScreen
              loops={loops}
              onComplete={(d) => {
                // Apply decisions to loops: remove anything not explicitly "kept".
                const removedIds = new Set(d.filter(x => x.outcome !== "kept").map(x => x.id));
                setLoops((prev) => prev.filter(l => !removedIds.has(l.id)));
                setDecisions(d);
                setScreen("complete");
              }}
              onExit={() => setScreen("loops")}
            />
          )}
          {screen === "complete" && (
            <CompleteScreen decisions={decisions} onBack={() => setScreen("loops")} />
          )}

          {/* Overlays */}
          {showShare && screen === "safari" && (
            <ShareSheet
              onClose={() => setShowShare(false)}
              onSelectTably={() => { setShowShare(false); setShowSave(true); }}
            />
          )}
          {showSave && (
            <SaveSheet
              onCancel={() => setShowSave(false)}
              onSave={handleSave}
              onSaveOnly={() => handleSave({ ...savedItem, reminder: "No reminder" })}
            />
          )}
          {activeLoop && screen === "loops" && (
            <LoopDetailSheet
              loop={loops.find(l => l.id === activeLoop.id) || activeLoop}
              onClose={() => setActiveLoop(null)}
              onOpenPage={() => { setActiveLoop(null); setScreen("safari"); }}
              onAction={(outcome) => {
                if (outcome !== "kept") {
                  setLoops((prev) => prev.filter(l => l.id !== activeLoop.id));
                }
                setActiveLoop(null);
              }}
            />
          )}
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
