<?php
// ==========================
// Feedback: append to INTEREST.md
// ==========================
$submitted = false;
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $suggestion = trim((string)($_POST['suggestion'] ?? ''));

    if ($suggestion !== '') {
        $digestDate = basename(__DIR__);
        $stamp = date('Y-m-d H:i:s');

        // Path: PHASE-05-ORCHESTRATOR/digests/archive/YYYY-MM-DD/ -> PHASE-03-DIGEST-CONTRACT/INTEREST.md
        $interestPath = __DIR__ . '/../../../../PHASE-03-DIGEST-CONTRACT/INTEREST.md';

        if (!file_exists($interestPath)) {
            $error = 'INTEREST.md not found';
        } else {
            $block = "\n\n## Addition from user on {$digestDate}\n";
            $block .= "**Submitted:** {$stamp}\n\n";
            $block .= $suggestion . "\n";

            if (@file_put_contents($interestPath, $block, FILE_APPEND | LOCK_EX) === false) {
                $error = 'Failed to write to INTEREST.md';
            } else {
                $submitted = true;
            }
        }
    }
}

// ==========================
// Load digest.json
// ==========================
$digestPath = __DIR__ . '/digest.json';
if (!file_exists($digestPath)) {
    http_response_code(500);
    echo '<h1>digest.json missing</h1>';
    exit;
}

$digestRaw = file_get_contents($digestPath);
$digest = json_decode((string)$digestRaw, true);
if (!is_array($digest)) {
    http_response_code(500);
    echo '<h1>digest.json invalid</h1>';
    exit;
}

$dateIso = (string)($digest['date'] ?? basename(__DIR__));
$title = (string)($digest['title'] ?? ('Twitter Digest - ' . $dateIso));
$generatedAt = (string)($digest['generated_at'] ?? '');
$sections = $digest['sections'] ?? [];
$closingHtml = (string)($digest['closing_html'] ?? '<p><strong>That is a wrap.</strong> See you tomorrow.</p>');

function esc($s) {
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

function display_date($dateIso) {
    $dt = date_create((string)$dateIso);
    if (!$dt) {
        return (string)$dateIso;
    }
    return $dt->format('l, F j, Y');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Your daily Twitter digest - curated tweets and insights">
    <meta name="theme-color" content="#1d9bf0">

    <title><?php echo esc($title); ?></title>

    <link rel="preconnect" href="https://platform.twitter.com">
    <meta name="twitter:widgets:theme" content="light">
    <meta name="twitter:widgets:border-color" content="transparent">

    <!-- Assets from twitter-app -->
    <link rel="icon" type="image/svg+xml" href="../../../../PHASE-04-RENDER/twitter-app/twitter-logo.svg">
    <link rel="stylesheet" href="../../../../PHASE-04-RENDER/twitter-app/styles.css">

    <style>
      .tweet-context {
        margin: 10px 0 8px;
        padding: 10px 12px;
        border: 1px solid rgba(0, 0, 0, 0.08);
        border-radius: 10px;
        background: rgba(255, 255, 255, 0.6);
      }
      [data-theme="dark"] .tweet-context {
        background: rgba(0, 0, 0, 0.15);
        border-color: rgba(255, 255, 255, 0.12);
      }
      .tweet-context__meta {
        display: flex;
        gap: 10px;
        align-items: center;
        flex-wrap: wrap;
        font-size: 13px;
        opacity: 0.8;
      }
      .tweet-context__meta a {
        text-decoration: none;
      }
      .tweet-context__text {
        margin-top: 8px;
        font-size: 15px;
        line-height: 1.6;
      }
      .tweet-context__why {
        margin-top: 8px;
        font-size: 14px;
        opacity: 0.9;
      }
    </style>
</head>
<body>
    <div class="container">
        <div class="main-card">

            <header class="digest-header content-item">
                <img src="../../../../PHASE-04-RENDER/twitter-app/twitter-logo.svg" alt="Twitter" class="digest-header__logo">
                <div class="digest-header__text">
                    <h1 class="digest-header__title">Twitter Digest</h1>
                    <time class="digest-header__date" datetime="<?php echo esc($dateIso); ?>">
                      <?php echo esc(display_date($dateIso)); ?>
                    </time>
                </div>
            </header>

            <?php if ($generatedAt !== ''): ?>
            <div class="narrative content-item">
                <p><em>Generated at <?php echo esc($generatedAt); ?></em></p>
            </div>
            <?php endif; ?>

            <?php foreach ((array)$sections as $section): ?>
                <?php
                $sectionId = (string)($section['id'] ?? '');
                $sectionIcon = (string)($section['icon'] ?? '');
                $sectionTitle = (string)($section['title'] ?? '');
                $sectionTags = (array)($section['tags'] ?? []);
                $sectionBlocks = (array)($section['blocks'] ?? []);
                if ($sectionId === '' || $sectionTitle === '') {
                    continue;
                }
                ?>
                <section aria-labelledby="<?php echo esc($sectionId); ?>">
                    <div class="topic-header content-item">
                        <span class="topic-header__icon" aria-hidden="true"><?php echo esc($sectionIcon); ?></span>
                        <h2 id="<?php echo esc($sectionId); ?>" class="topic-header__label"><?php echo esc($sectionTitle); ?></h2>
                    </div>

                    <?php if (!empty($sectionTags)): ?>
                    <div class="topic-tags content-item">
                        <?php foreach ($sectionTags as $tag): ?>
                            <span class="topic-tag"><?php echo esc($tag); ?></span>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>

                    <?php foreach ($sectionBlocks as $block): ?>
                        <?php $blockType = (string)($block['type'] ?? ''); ?>
                        <?php if ($blockType === 'narrative'): ?>
                            <div class="narrative content-item">
                                <?php echo (string)($block['html'] ?? ''); ?>
                            </div>
                        <?php elseif ($blockType === 'tweet'): ?>
                            <?php $t = (array)($block['tweet'] ?? []); ?>
                            <?php $tweetUrl = (string)($t['tweet_url'] ?? ''); ?>
                            <div class="tweet-context content-item content-item--fast">
                                <div class="tweet-context__meta">
                                    <span><strong><?php echo esc((string)($t['name'] ?? '')); ?></strong></span>
                                    <span><?php echo esc((string)($t['username'] ?? '')); ?></span>
                                    <?php if (!empty($t['created_at'])): ?>
                                      <time datetime="<?php echo esc((string)$t['created_at']); ?>"><?php echo esc(substr((string)$t['created_at'], 0, 10)); ?></time>
                                    <?php endif; ?>
                                    <?php if ($tweetUrl !== ''): ?>
                                      <a href="<?php echo esc($tweetUrl); ?>" target="_blank" rel="noopener noreferrer">Open</a>
                                    <?php endif; ?>
                                    <span>Likes <?php echo esc((string)($t['likes'] ?? 0)); ?></span>
                                    <span>Retweets <?php echo esc((string)($t['retweets'] ?? 0)); ?></span>
                                    <span>Replies <?php echo esc((string)($t['replies'] ?? 0)); ?></span>
                                </div>
                                <div class="tweet-context__text"><?php echo nl2br(esc((string)($t['content'] ?? ''))); ?></div>
                                <?php if (!empty($t['why'])): ?>
                                  <div class="tweet-context__why"><strong>Why it matters:</strong> <?php echo esc((string)$t['why']); ?></div>
                                <?php endif; ?>
                                <?php if (!empty($t['image_description'])): ?>
                                  <div class="tweet-context__why"><strong>Images:</strong> <?php echo esc((string)$t['image_description']); ?></div>
                                <?php endif; ?>
                            </div>

                            <?php if ($tweetUrl !== ''): ?>
                            <div class="tweet-container content-item">
                                <blockquote class="twitter-tweet"><a href="<?php echo esc($tweetUrl); ?>"></a></blockquote>
                            </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </section>
            <?php endforeach; ?>

            <div class="narrative narrative--closing content-item">
                <?php echo $closingHtml; ?>
            </div>

            <?php if ($submitted): ?>
              <div class="narrative content-item"><p><strong>Thanks.</strong> Your suggestion was appended to INTEREST.md.</p></div>
            <?php elseif ($error): ?>
              <div class="narrative content-item"><p><strong>Error:</strong> <?php echo esc($error); ?></p></div>
            <?php endif; ?>

            <form method="POST" class="feedback content-item" data-feedback>
                <button type="button" class="feedback__trigger" data-feedback-trigger>
                    Suggest changes for tomorrow
                </button>
                <div class="feedback__content" data-feedback-content>
                    <textarea
                        name="suggestion"
                        class="feedback__textarea"
                        placeholder="What would you like me to change? More of something, less of another, different topics..."
                        aria-label="Your feedback"
                        required
                    ></textarea>
                    <div class="feedback__actions">
                        <button type="button" class="btn btn--secondary" data-feedback-cancel>Cancel</button>
                        <button type="submit" class="btn btn--primary">Send</button>
                    </div>
                </div>
            </form>

        </div>
    </div>

    <script async src="https://platform.twitter.com/widgets.js"></script>
    <script src="../../../../PHASE-04-RENDER/twitter-app/app.js"></script>
</body>
</html>
