Spaces:
Paused

File size: 28,002 Bytes
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091ca1d
2a99443
 
 
 
 
 
 
 
d753528
2a99443
d753528
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d753528
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091ca1d
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
579285c
2a99443
579285c
2a99443
579285c
2a99443
 
 
 
091ca1d
c85f9e9
 
 
2a99443
c85f9e9
2a99443
 
 
 
 
 
 
c85f9e9
 
2a99443
 
c85f9e9
 
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091ca1d
2a99443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
"""
Case Content Blocks API
=======================
Universal, domain-agnostic rich content blocks that attach to any case.

Each block can hold any data type:
  text · heading · image · gallery · table · code · video · audio
  file · embed · metric · checklist · chart · quote · divider
  message · link_card · timeline · kanban

Prefix : /api/v1/cases/blocks
Auth   : JWT cookie OR Bearer header (required)
Perf   : SQLite, indexed on (tenant_id, case_id, position)
"""

from __future__ import annotations

import json
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
from uuid import uuid4

import jwt as pyjwt
from fastapi import APIRouter, HTTPException, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel, Field

from core.helpers import JWT_ALGO, JWT_SECRET, get_sqlite as _db

router = APIRouter(prefix="/api/v1/cases/blocks", tags=["Case Content Blocks"])

# ── Icons for each block type ─────────────────────────────────────────────────
BLOCK_META: Dict[str, Dict[str, str]] = {
    "text":       {"icon": "📝", "label": "Text"},
    "heading":    {"icon": "🔤", "label": "Heading"},
    "image":      {"icon": "🖼",  "label": "Image"},
    "gallery":    {"icon": "🗂",  "label": "Gallery"},
    "table":      {"icon": "⊞",  "label": "Table"},
    "code":       {"icon": "💻", "label": "Code"},
    "video":      {"icon": "🎬", "label": "Video"},
    "audio":      {"icon": "🎵", "label": "Audio"},
    "file":       {"icon": "📎", "label": "File"},
    "embed":      {"icon": "🔗", "label": "Embed"},
    "metric":     {"icon": "📊", "label": "Metric"},
    "checklist":  {"icon": "☑️", "label": "Checklist"},
    "chart":      {"icon": "📈", "label": "Chart"},
    "quote":      {"icon": "❝",  "label": "Quote"},
    "divider":    {"icon": "—",  "label": "Divider"},
    "message":    {"icon": "💬", "label": "Message"},
    "link_card":  {"icon": "🔗", "label": "Link Card"},
    "timeline":   {"icon": "📅", "label": "Timeline"},
    "kanban":     {"icon": "🗃",  "label": "Kanban"},
    "short":      {"icon": "🎥", "label": "Short Video"},
}


# ── DB helpers ────────────────────────────────────────────────────────────────


def _ensure_tables() -> None:
    with _db() as c:
        c.execute("""
            CREATE TABLE IF NOT EXISTS case_content_blocks (
                id           TEXT PRIMARY KEY,
                tenant_id    TEXT NOT NULL,
                case_id      TEXT NOT NULL,
                case_domain  TEXT DEFAULT '',
                user_id      TEXT NOT NULL,
                block_type   TEXT DEFAULT 'text',
                title        TEXT,
                content      TEXT DEFAULT '{}',
                position     INTEGER DEFAULT 0,
                is_pinned    INTEGER DEFAULT 0,
                is_visible   INTEGER DEFAULT 1,
                tags         TEXT,
                created_at   TEXT,
                updated_at   TEXT,
                deleted_at   TEXT
            )
        """)
        c.execute("""
            CREATE TABLE IF NOT EXISTS case_interests (
                id           TEXT PRIMARY KEY,
                tenant_id    TEXT NOT NULL,
                user_id      TEXT NOT NULL,
                case_id      TEXT NOT NULL,
                case_domain  TEXT DEFAULT '',
                interest_type TEXT DEFAULT 'starred',
                created_at   TEXT
            )
        """)
        c.execute("CREATE INDEX IF NOT EXISTS idx_ccb_case ON case_content_blocks(tenant_id, case_id)")
        c.execute("CREATE INDEX IF NOT EXISTS idx_ccb_pos  ON case_content_blocks(case_id, position)")
        c.execute("CREATE INDEX IF NOT EXISTS idx_ci_user  ON case_interests(tenant_id, user_id)")
        c.commit()


try:
    _ensure_tables()
except Exception:
    pass


def _auth(request: Request) -> dict:
    raw = ""
    h = request.headers.get("Authorization", "")
    if h.startswith("Bearer "):
        raw = h[7:]
    else:
        raw = request.cookies.get("access_token", "").replace("Bearer ", "")
    if not raw:
        raise HTTPException(status_code=401, detail="Not authenticated")
    try:
        return pyjwt.decode(raw, JWT_SECRET, algorithms=[JWT_ALGO])
    except Exception:
        raise HTTPException(status_code=401, detail="Session expired")


def _row(r) -> dict:
    d = dict(r)
    try:
        d["content"] = json.loads(d.get("content") or "{}")
    except Exception:
        d["content"] = {}
    d["is_pinned"] = bool(d.get("is_pinned", 0))
    d["is_visible"] = bool(d.get("is_visible", 1))
    return d


# ── Pydantic schemas ──────────────────────────────────────────────────────────

class BlockCreate(BaseModel):
    case_id: str
    case_domain: str = ""
    block_type: str = "text"
    title: Optional[str] = None
    content: Dict[str, Any] = Field(default_factory=dict)
    position: Optional[int] = None
    tags: Optional[str] = None


class BlockUpdate(BaseModel):
    title: Optional[str] = None
    content: Optional[Dict[str, Any]] = None
    position: Optional[int] = None
    is_pinned: Optional[bool] = None
    is_visible: Optional[bool] = None
    tags: Optional[str] = None


class InterestToggle(BaseModel):
    case_id: str
    case_domain: str = ""
    interest_type: str = "starred"   # starred | watching | assigned


# ── Endpoints ─────────────────────────────────────────────────────────────────

@router.get("/{case_id}")
async def list_blocks(
    case_id: str,
    request: Request,
    domain: Optional[str] = Query(None),
):
    """
    List content blocks for a case.
    Returns HTML fragment for HTMX requests, JSON list for API clients.
    """
    _auth(request)
    with _db() as c:
        rows = c.execute(
            "SELECT * FROM case_content_blocks "
            "WHERE case_id=? AND deleted_at IS NULL AND is_visible=1 "
            "ORDER BY position ASC, created_at ASC",
            (case_id,),
        ).fetchall()
    blocks = [_row(r) for r in rows]

    if request.headers.get("hx-request") or "text/html" in request.headers.get("accept", ""):
        return _render_blocks_html(blocks, case_id)
    return blocks


@router.post("", status_code=201)
async def create_block(body: BlockCreate, request: Request):
    """Add a new content block to a case."""
    user = _auth(request)

    if body.position is None:
        with _db() as c:
            r = c.execute(
                "SELECT COALESCE(MAX(position),0) AS mp FROM case_content_blocks "
                "WHERE case_id=? AND deleted_at IS NULL",
                (body.case_id,),
            ).fetchone()
        position = (r["mp"] or 0) + 10
    else:
        position = body.position

    bid = str(uuid4())
    now = datetime.now(timezone.utc).isoformat()
    tid = user.get("tenant_id") or "default"
    uid = user.get("sub", "")

    with _db() as c:
        c.execute(
            "INSERT INTO case_content_blocks "
            "(id,tenant_id,case_id,case_domain,user_id,block_type,title,content,"
            "position,is_pinned,is_visible,tags,created_at,updated_at) "
            "VALUES (?,?,?,?,?,?,?,?,?,0,1,?,?,?)",
            (bid, tid, body.case_id, body.case_domain, uid,
             body.block_type, body.title, json.dumps(body.content),
             position, body.tags, now, now),
        )
        c.commit()
    return {"id": bid, "position": position, "block_type": body.block_type}


@router.patch("/{block_id}")
async def update_block(block_id: str, body: BlockUpdate, request: Request):
    """Update a content block's content, position, or visibility."""
    _auth(request)
    updates, values = [], []
    if body.title is not None:
        updates.append("title=?"); values.append(body.title)
    if body.content is not None:
        updates.append("content=?"); values.append(json.dumps(body.content))
    if body.position is not None:
        updates.append("position=?"); values.append(body.position)  # type: ignore[arg-type, assignment]
    if body.is_pinned is not None:
        updates.append("is_pinned=?"); values.append(int(body.is_pinned))  # type: ignore[arg-type, assignment]
    if body.is_visible is not None:
        updates.append("is_visible=?"); values.append(int(body.is_visible))  # type: ignore[arg-type, assignment]
    if body.tags is not None:
        updates.append("tags=?"); values.append(body.tags)
    if not updates:
        raise HTTPException(status_code=400, detail="Nothing to update")
    updates.append("updated_at=?"); values.append(datetime.now(timezone.utc).isoformat())
    user = _auth(request)
    tid = user.get("tenant_id") or "default"
    values.extend([block_id, tid])
    with _db() as c:
        c.execute(f"UPDATE case_content_blocks SET {', '.join(updates)} WHERE id=? AND tenant_id=?", values)
        c.commit()
    return {"id": block_id, "updated": True}


@router.delete("/{block_id}", status_code=204)
async def delete_block(block_id: str, request: Request):
    """Soft-delete a content block."""
    user = _auth(request)
    tid = user.get("tenant_id") or "default"
    with _db() as c:
        c.execute(
            "UPDATE case_content_blocks SET deleted_at=? WHERE id=? AND tenant_id=?",
            (datetime.now(timezone.utc).isoformat(), block_id, tid),
        )
        c.commit()


# ── Interest / Star API ───────────────────────────────────────────────────────

@router.post("/interests/toggle")
async def toggle_interest(body: InterestToggle, request: Request):
    """Star / unstar a case for the current user."""
    user = _auth(request)
    uid = user.get("sub", "")
    tid = user.get("tenant_id") or "default"

    with _db() as c:
        existing = c.execute(
            "SELECT id FROM case_interests WHERE user_id=? AND case_id=? AND interest_type=?",
            (uid, body.case_id, body.interest_type),
        ).fetchone()
        if existing:
            c.execute("DELETE FROM case_interests WHERE id=?", (existing["id"],))
            c.commit()
            return {"action": "removed", "case_id": body.case_id}
        else:
            c.execute(
                "INSERT INTO case_interests (id,tenant_id,user_id,case_id,case_domain,interest_type,created_at) "
                "VALUES (?,?,?,?,?,?,?)",
                (str(uuid4()), tid, uid, body.case_id, body.case_domain,
                 body.interest_type, datetime.now(timezone.utc).isoformat()),
            )
            c.commit()
            return {"action": "added", "case_id": body.case_id}


@router.get("/interests/mine")
async def my_interests(request: Request):
    """List all cases the current user has starred."""
    user = _auth(request)
    uid = user.get("sub", "")
    with _db() as c:
        rows = c.execute(
            "SELECT case_id, case_domain, interest_type, created_at "
            "FROM case_interests WHERE user_id=? ORDER BY created_at DESC",
            (uid,),
        ).fetchall()
    return [dict(r) for r in rows]


# ── HTML Render Helpers ───────────────────────────────────────────────────────

def _render_blocks_html(blocks: list, case_id: str) -> HTMLResponse:
    if not blocks:
        return HTMLResponse(
            '<div style="text-align:center;padding:48px 20px;color:var(--text-muted);">'
            '<div style="font-size:40px;margin-bottom:12px;">✨</div>'
            '<div style="font-size:15px;font-weight:600;color:var(--text);margin-bottom:6px;">'
            'Blank canvas — start building</div>'
            '<div style="font-size:13px;">Add text, images, tables, metrics and more '
            'using the toolbar above.</div>'
            '</div>'
        )

    items = []
    for b in blocks:
        btype = b.get("block_type", "text")
        meta = BLOCK_META.get(btype, {"icon": "📄", "label": btype.title()})
        icon = meta["icon"]
        label = meta["label"]
        title = b.get("title") or ""
        content = b.get("content") or {}
        bid = b["id"]
        pin = "📌 " if b.get("is_pinned") else ""
        body_html = _render_body(btype, content, case_id)

        items.append(
            f'<div class="ws-block" data-id="{bid}" data-type="{btype}" id="blk-{bid}">'
            f'<div class="ws-block-hdr">'
            f'<span class="ws-blk-icon">{icon}</span>'
            f'<span class="ws-blk-lbl">{pin}{label.upper()}</span>'
            f'{f"<span class=\"ws-blk-title\">{title}</span>" if title else ""}'
            f'<div class="ws-blk-acts">'
            f'<button onclick="wsPin(\'{bid}\')" title="Pin" class="ws-act-btn">📌</button>'
            f'<button onclick="wsDelete(\'{bid}\',this)" title="Delete" class="ws-act-btn del">🗑</button>'
            f'</div>'
            f'</div>'
            f'<div class="ws-block-body">{body_html}</div>'
            f'</div>'
        )
    return HTMLResponse("\n".join(items))


def _render_body(btype: str, c: dict, case_id: str = "") -> str:
    if btype == "text":
        body = c.get("body", "")
        return f'<div class="ws-text">{body}</div>'

    elif btype == "heading":
        lvl = min(max(int(c.get("level", 2)), 1), 4)
        txt = c.get("text", "")
        sizes = {1: "22px", 2: "18px", 3: "15px", 4: "13px"}
        fw = {1: "800", 2: "700", 3: "600", 4: "600"}
        return (f'<div style="font-size:{sizes[lvl]};font-weight:{fw[lvl]};'
                f'color:var(--text);line-height:1.3;">{txt}</div>')

    elif btype == "image":
        url = c.get("url", "")
        cap = c.get("caption", "")
        if not url:
            return '<div class="ws-empty">No image URL set.</div>'
        cap_html = (f'<div style="font-size:11px;color:var(--text-muted);margin-top:6px;'
                    f'text-align:center;">{cap}</div>') if cap else ""
        return f'<img src="{url}" alt="{cap}" style="max-width:100%;border-radius:8px;">{cap_html}'

    elif btype == "gallery":
        imgs = c.get("images", [])
        if not imgs:
            return '<div class="ws-empty">No images in gallery.</div>'
        cols = '<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:8px;">'
        for img in imgs:
            u = img.get("url", "")
            cp = img.get("caption", "")
            cols += (f'<div style="position:relative;">'
                     f'<img src="{u}" alt="{cp}" style="width:100%;height:110px;object-fit:cover;border-radius:6px;">'
                     f'{"<div style=\"font-size:10px;color:var(--text-muted);margin-top:3px;\">"+cp+"</div>" if cp else ""}'
                     f'</div>')
        return cols + "</div>"

    elif btype == "table":
        headers = c.get("headers", [])
        rows = c.get("rows", [])
        if not headers and not rows:
            return '<div class="ws-empty">Empty table.</div>'
        ths = "".join(
            f'<th style="padding:8px 12px;text-align:left;font-size:11px;font-weight:700;'
            f'text-transform:uppercase;letter-spacing:.3px;white-space:nowrap;">{h}</th>'
            for h in headers
        )
        trs = "".join(
            '<tr>' + "".join(
                f'<td style="padding:8px 12px;font-size:13px;border-top:1px solid var(--border);">{cell}</td>'
                for cell in row
            ) + '</tr>'
            for row in rows
        )
        return (f'<div style="overflow-x:auto;">'
                f'<table style="width:100%;border-collapse:collapse;">'
                f'<thead><tr style="background:var(--bg);">{ths}</tr></thead>'
                f'<tbody>{trs}</tbody></table></div>')

    elif btype == "metric":
        label = c.get("label", "Metric")
        value = c.get("value", "—")
        unit = c.get("unit", "")
        trend = c.get("trend", "")
        color = c.get("color", "var(--primary)")
        trend_icon = {"up": "↑", "down": "↓", "stable": "→"}.get(trend, "")
        trend_color = {"up": "#56a066", "down": "#c74b4b", "stable": "#c2883b"}.get(trend, "var(--text-muted)")
        return (
            f'<div style="display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;">'
            f'<span style="font-size:32px;font-weight:800;color:{color};line-height:1;">{value}</span>'
            f'<span style="font-size:14px;color:var(--text-muted);">{unit}</span>'
            f'<span style="font-size:14px;color:{trend_color};font-weight:700;">{trend_icon}</span>'
            f'</div>'
            f'<div style="font-size:12px;color:var(--text-muted);margin-top:4px;">{label}</div>'
        )

    elif btype == "code":
        lang = c.get("language", "")
        code = c.get("code", "")
        lang_badge = (f'<span style="font-size:10px;font-weight:700;text-transform:uppercase;'
                      f'color:var(--primary);margin-bottom:6px;display:block;">{lang}</span>') if lang else ""
        return (f'<div>{lang_badge}</div>'
                f'<pre style="background:var(--bg);border-radius:6px;padding:14px;overflow-x:auto;'
                f'font-size:12px;line-height:1.6;font-family:Courier New,monospace;margin:0;">'
                f'<code>{code}</code></pre>')

    elif btype == "video":
        url = c.get("url", "")
        title = c.get("title", "Video")
        if not url:
            return '<div class="ws-empty">No video URL.</div>'
        if "youtube.com" in url or "youtu.be" in url:
            vid = url.split("v=")[-1].split("&")[0] if "v=" in url else url.split("/")[-1]
            return (f'<div style="position:relative;padding-top:56.25%;border-radius:8px;overflow:hidden;">'
                    f'<iframe src="https://www.youtube.com/embed/{vid}" allowfullscreen '
                    f'style="position:absolute;top:0;left:0;width:100%;height:100%;border:none;"></iframe></div>')
        return f'<video src="{url}" controls style="max-width:100%;border-radius:8px;" title="{title}"></video>'

    elif btype == "short":
        url = c.get("url", "")
        title = c.get("title", "Short")
        if not url:
            return '<div class="ws-empty">No video URL.</div>'
        return (f'<div style="max-width:320px;margin:0 auto;">'
                f'<video src="{url}" controls loop style="width:100%;border-radius:12px;aspect-ratio:9/16;">'
                f'</video>'
                f'<div style="font-size:12px;color:var(--text-muted);text-align:center;margin-top:6px;">{title}</div>'
                f'</div>')

    elif btype == "audio":
        url = c.get("url", "")
        title = c.get("title", "Audio")
        return (f'<div style="background:var(--bg);border-radius:8px;padding:12px 16px;">'
                f'<div style="font-size:12px;font-weight:600;color:var(--text);margin-bottom:8px;">🎵 {title}</div>'
                f'<audio src="{url}" controls style="width:100%;"></audio></div>')

    elif btype == "file":
        name = c.get("name", "File")
        url = c.get("url", "#")
        size = c.get("size", 0)
        size_str = f" · {size // 1024} KB" if size else ""
        mime = c.get("mime_type", "")
        ext = name.rsplit(".", 1)[-1].upper() if "." in name else "FILE"
        return (f'<a href="{url}" target="_blank" '
                f'style="display:inline-flex;align-items:center;gap:10px;'
                f'padding:10px 16px;border:1px solid var(--border);border-radius:8px;'
                f'text-decoration:none;color:var(--text);">'
                f'<span style="padding:4px 8px;background:var(--primary);color:#fff;'
                f'border-radius:4px;font-size:10px;font-weight:700;">{ext}</span>'
                f'<span style="font-size:13px;font-weight:500;">{name}</span>'
                f'<span style="font-size:11px;color:var(--text-muted);">{size_str}</span>'
                f'</a>')

    elif btype == "embed":
        url = c.get("url", "")
        title = c.get("title", "Embedded content")
        return (f'<div style="border:1px solid var(--border);border-radius:8px;overflow:hidden;">'
                f'<div style="padding:8px 12px;background:var(--bg);display:flex;align-items:center;'
                f'gap:8px;font-size:12px;color:var(--text-muted);">'
                f'🔗 <a href="{url}" target="_blank" style="color:var(--primary);">{title}</a></div>'
                f'<iframe src="{url}" style="width:100%;height:320px;border:none;"'
                f' sandbox="allow-scripts allow-same-origin allow-popups"></iframe></div>')

    elif btype == "checklist":
        items_list = c.get("items", [])
        if not items_list:
            return '<div class="ws-empty">Empty checklist.</div>'
        done = sum(1 for i in items_list if i.get("done"))
        pct = round(done / len(items_list) * 100) if items_list else 0
        progress = (f'<div style="margin-bottom:10px;">'
                    f'<div style="display:flex;justify-content:space-between;font-size:11px;'
                    f'color:var(--text-muted);margin-bottom:4px;">'
                    f'<span>Progress</span><span>{done}/{len(items_list)}</span></div>'
                    f'<div style="height:4px;background:var(--border);border-radius:2px;">'
                    f'<div style="height:4px;width:{pct}%;background:#56a066;border-radius:2px;'
                    f'transition:width .3s;"></div></div></div>')
        lis = "".join(
            f'<div style="display:flex;gap:10px;align-items:flex-start;padding:5px 0;">'
            f'<span style="font-size:16px;flex-shrink:0;">{"✅" if item.get("done") else "⬜"}</span>'
            f'<span style="font-size:13px;{"text-decoration:line-through;color:var(--text-muted);" if item.get("done") else "color:var(--text);"}">'
            f'{item.get("text", "")}</span></div>'
            for item in items_list
        )
        return progress + lis

    elif btype == "chart":
        chart_type = c.get("type", "bar")
        labels = c.get("labels", [])
        datasets = c.get("datasets", [])
        if not labels:
            return '<div class="ws-empty">No chart data.</div>'
        cid = f"chart-{uuid4().hex[:8]}"
        chart_data = json.dumps({"type": chart_type, "data": {"labels": labels, "datasets": datasets},
                                  "options": {"responsive": True, "maintainAspectRatio": True}})
        return (f'<div style="max-height:280px;">'
                f'<canvas id="{cid}" height="200"></canvas></div>'
                f'<script>if(window.Chart){{new Chart(document.getElementById("{cid}"),{chart_data})}}</script>')

    elif btype == "quote":
        text = c.get("text", "")
        author = c.get("author", "")
        return (f'<blockquote style="border-left:4px solid var(--primary);padding:10px 16px;margin:0;'
                f'font-style:italic;font-size:15px;color:var(--text);">{text}'
                f'{"<footer style=\"font-size:12px;font-style:normal;color:var(--text-muted);margin-top:8px;\">— "+author+"</footer>" if author else ""}'
                f'</blockquote>')

    elif btype == "divider":
        label = c.get("label", "")
        if label:
            return (f'<div style="display:flex;align-items:center;gap:12px;padding:4px 0;">'
                    f'<hr style="flex:1;border:none;border-top:1px solid var(--border);">'
                    f'<span style="font-size:11px;font-weight:600;color:var(--text-muted);'
                    f'text-transform:uppercase;letter-spacing:.5px;">{label}</span>'
                    f'<hr style="flex:1;border:none;border-top:1px solid var(--border);"></div>')
        return '<hr style="border:none;border-top:2px dashed var(--border);margin:4px 0;">'

    elif btype == "message":
        text = c.get("text", "")
        author = c.get("author", "")
        ts = c.get("timestamp", "")
        return (f'<div style="background:var(--bg);border-radius:10px;padding:12px 14px;">'
                f'<div style="display:flex;align-items:center;gap:8px;margin-bottom:6px;">'
                f'<div style="width:28px;height:28px;border-radius:50%;background:var(--primary);'
                f'color:#fff;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;">'
                f'{author[:1].upper() if author else "?"}</div>'
                f'<span style="font-size:13px;font-weight:600;color:var(--text);">{author}</span>'
                f'{"<span style=\"font-size:11px;color:var(--text-muted);\">"+ts+"</span>" if ts else ""}'
                f'</div>'
                f'<div style="font-size:13px;color:var(--text);line-height:1.5;padding-left:36px;">{text}</div>'
                f'</div>')

    elif btype == "link_card":
        url = c.get("url", "#")
        title = c.get("title", url)
        desc = c.get("description", "")
        img = c.get("image", "")
        img_html = (f'<img src="{img}" style="width:60px;height:60px;object-fit:cover;'
                    f'border-radius:6px;flex-shrink:0;" alt="">') if img else ""
        return (f'<a href="{url}" target="_blank" '
                f'style="display:flex;gap:12px;align-items:center;padding:12px 14px;'
                f'border:1px solid var(--border);border-radius:10px;text-decoration:none;'
                f'transition:box-shadow .15s;" '
                f'onmouseover="this.style.boxShadow=\'0 2px 8px rgba(0,0,0,.08)\'" '
                f'onmouseout="this.style.boxShadow=\'none\'">'
                f'{img_html}'
                f'<div style="flex:1;min-width:0;">'
                f'<div style="font-size:13px;font-weight:600;color:var(--text);'
                f'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">{title}</div>'
                f'{"<div style=\"font-size:12px;color:var(--text-muted);margin-top:2px;\">"+desc+"</div>" if desc else ""}'
                f'<div style="font-size:11px;color:var(--primary);margin-top:4px;">{url[:60]}…</div>'
                f'</div></a>')

    elif btype == "timeline":
        events = c.get("events", [])
        if not events:
            return '<div class="ws-empty">No timeline events.</div>'
        items = []
        for ev in events:
            ts = ev.get("date", "")
            label = ev.get("label", "")
            desc = ev.get("description", "")
            done = ev.get("done", False)
            color = "#56a066" if done else "var(--border)"
            items.append(
                f'<div style="display:flex;gap:12px;padding-bottom:16px;">'
                f'<div style="display:flex;flex-direction:column;align-items:center;flex-shrink:0;">'
                f'<div style="width:12px;height:12px;border-radius:50%;background:{color};'
                f'border:2px solid {color};flex-shrink:0;margin-top:3px;"></div>'
                f'<div style="width:2px;flex:1;background:var(--border);margin-top:4px;"></div></div>'
                f'<div style="padding-bottom:4px;">'
                f'<div style="font-size:13px;font-weight:600;color:var(--text);">{label}</div>'
                f'{"<div style=\"font-size:11px;color:var(--text-muted);\">"+ts+"</div>" if ts else ""}'
                f'{"<div style=\"font-size:12px;color:var(--text);margin-top:3px;\">"+desc+"</div>" if desc else ""}'
                f'</div></div>'
            )
        return "".join(items)

    else:
        raw = str(c)[:300]
        return f'<div style="font-size:12px;color:var(--text-muted);font-family:monospace;">{raw}</div>'