function ListsPage() {
  const { AppBootstrap } = window.__CRM__;
  const {
    Container, Paper, Typography, TextField, Button, Table, TableHead, TableRow, TableCell, TableBody,
    IconButton, Stack, Pagination, TableContainer, useMediaQuery, Card, CardContent, Divider, Dialog,
    DialogTitle, DialogContent, DialogActions
  } = MaterialUI;

  const isXs = useMediaQuery('(max-width:600px)');
  const isSm = useMediaQuery('(max-width:900px)');

  const [q, setQ] = React.useState("");
  const [rows, setRows] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [page, setPage] = React.useState(1);
  const limit = 25;

  // rename modal
  const [renameOpen, setRenameOpen] = React.useState(false);
  const [renameTarget, setRenameTarget] = React.useState({ id: 0, name: "" });
  const [newName, setNewName] = React.useState("");

  // NEW LIST modal
  const [newOpen, setNewOpen] = React.useState(false);
  const [newListName, setNewListName] = React.useState("");

  async function load(p = 1) {
    const offset = (p - 1) * limit;
    const res = await fetch(`/api/lists_list.php?q=${encodeURIComponent(q)}&limit=${limit}&offset=${offset}`, { credentials: 'include' });
    const j = await res.json();
    setRows(j.items || []); setTotal(j.total || 0); setPage(p);
  }
  React.useEffect(() => { load(1); }, []);

  // New List (modal)
  function openNew() { setNewListName(""); setNewOpen(true); }
  async function createNew() {
    const name = newListName.trim();
    if (!name) return;
    const fd = new FormData(); fd.append('name', name);
    const r = await fetch('/api/lists_create.php', { method:'POST', body: fd, credentials:'include' });
    const j = await r.json();
    if (j.ok) { setNewOpen(false); location.hash = `#/lists/${j.id}`; }
  }

  // Rename
  function openRename(row) { setRenameTarget(row); setNewName(row.name); setRenameOpen(true); }
  async function doRename() {
    const name = newName.trim(); if (!name) return;
    const fd = new FormData(); fd.append('id', String(renameTarget.id)); fd.append('name', name);
    await fetch('/api/lists_rename.php', { method:'POST', body: fd, credentials:'include' });
    setRenameOpen(false); load(page);
  }

  // Delete
  async function onDelete(id) {
    if (!confirm('Delete this list? This cannot be undone.')) return;
    const fd = new FormData(); fd.append('id', String(id));
    const r = await fetch('/api/lists_delete.php', { method:'POST', body: fd, credentials:'include' });
    if (r.status === 409) { alert('Cannot delete. Linked to a campaign.'); return; }
    if (!r.ok) { alert('Failed to delete'); return; }
    load(1);
  }

  // Download
  function onDownload(id) { location.href = `/api/lists_export.php?id=${encodeURIComponent(id)}`; }
  function onEditContacts(id) { location.hash = `#/lists/${id}`; }

  const pages = Math.max(1, Math.ceil(total/limit));

  const CardRow = ({ r }) => (
    <Card variant="outlined" sx={{ mb: 1, borderRadius: 2 }}>
      <CardContent sx={{ p: 2 }}>
        <Stack direction="row" justifyContent="space-between" alignItems="center">
          <Typography variant="subtitle1" sx={{ fontWeight: 700, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
            {r.name}
          </Typography>
          <Typography variant="body2" color="text.secondary">{r.total_contacts} contacts</Typography>
        </Stack>
        <Divider sx={{ my: 1 }} />
        <Stack direction="row" spacing={1} justifyContent="flex-end">
          <IconButton size="small" onClick={() => onDownload(r.id)} title="Download CSV"><span class="material-icons">download</span></IconButton>
          <IconButton size="small" onClick={() => onEditContacts(r.id)} title="Edit contacts"><span class="material-icons">group</span></IconButton>
          <IconButton size="small" onClick={() => openRename(r)} title="Edit name"><span class="material-icons">edit</span></IconButton>
          <IconButton size="small" onClick={() => onDelete(r.id)} title="Delete"><span class="material-icons">delete</span></IconButton>
        </Stack>
      </CardContent>
    </Card>
  );

  return (
    <AppBootstrap>
      <Container maxWidth="xl" sx={{ py: 3 }}>
        <Stack direction={{ xs:'column', md:'row' }} spacing={2} alignItems={{ xs:'stretch', md:'center' }} justifyContent="space-between" sx={{ mb: 2 }}>
          <Typography variant="h5" sx={{ fontWeight: 700 }}>Lists</Typography>
          <Stack direction="row" spacing={1} flexWrap="wrap">
            <TextField size="small" placeholder="Search by list name" value={q} onChange={e=>setQ(e.target.value)} />
            <Button variant="outlined" onClick={()=>load(1)}>Search</Button>
            <Button variant="contained" onClick={openNew}>New List</Button>
          </Stack>
        </Stack>

        {isXs ? (
          <div>
            {rows.length === 0
              ? <Typography sx={{ p: 2 }} color="text.secondary">No lists.</Typography>
              : rows.map(r => <CardRow key={r.id} r={r} />)}
          </div>
        ) : (
          <Paper>
            <TableContainer sx={{ maxHeight: isSm ? 520 : 'none' }}>
              <Table size="small" stickyHeader>
                <TableHead>
                  <TableRow>
                    <TableCell>Name</TableCell>
                    <TableCell width="180">Total Contacts</TableCell>
                    <TableCell align="right" width="200">Actions</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {rows.map(r => (
                    <TableRow key={r.id} hover>
                      <TableCell sx={{ maxWidth: 420, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{r.name}</TableCell>
                      <TableCell>{r.total_contacts}</TableCell>
                      <TableCell align="right">
                        <Stack direction="row" spacing={1} justifyContent="flex-end">
                          <IconButton size="small" onClick={() => onDownload(r.id)} title="Download CSV"><span class="material-icons">download</span></IconButton>
                          <IconButton size="small" onClick={() => onEditContacts(r.id)} title="Edit contacts"><span class="material-icons">group</span></IconButton>
                          <IconButton size="small" onClick={() => openRename(r)} title="Edit name"><span class="material-icons">edit</span></IconButton>
                          <IconButton size="small" onClick={() => onDelete(r.id)} title="Delete"><span class="material-icons">delete</span></IconButton>
                        </Stack>
                      </TableCell>
                    </TableRow>
                  ))}
                  {rows.length === 0 && (
                    <TableRow><TableCell colSpan={3}><Typography sx={{ p: 2 }} color="text.secondary">No lists.</Typography></TableCell></TableRow>
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </Paper>
        )}

        <Stack alignItems="center" sx={{ mt: 2 }}>
          <Pagination count={pages} page={page} onChange={(_, p)=>load(p)} />
        </Stack>
      </Container>

      {/* New List modal */}
      <Dialog open={newOpen} onClose={()=>setNewOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle>New List</DialogTitle>
        <DialogContent dividers>
          <TextField
            label="List name"
            value={newListName}
            onChange={e=>setNewListName(e.target.value)}
            fullWidth autoFocus
            onKeyDown={(e)=>{ if(e.key==='Enter'){ e.preventDefault(); createNew(); } }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={()=>setNewOpen(false)}>Cancel</Button>
          <Button variant="contained" onClick={createNew} disabled={!newListName.trim()}>Create</Button>
        </DialogActions>
      </Dialog>

      {/* Rename dialog */}
      <Dialog open={renameOpen} onClose={()=>setRenameOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle>Edit List Name</DialogTitle>
        <DialogContent dividers>
          <TextField label="Name" value={newName} onChange={e=>setNewName(e.target.value)} fullWidth autoFocus
            onKeyDown={(e)=>{ if(e.key==='Enter'){ e.preventDefault(); doRename(); } }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={()=>setRenameOpen(false)}>Cancel</Button>
          <Button variant="contained" onClick={doRename} disabled={!newName.trim()}>Save</Button>
        </DialogActions>
      </Dialog>
    </AppBootstrap>
  );
}
window.ListsPage = ListsPage;
